File handling is a crucial aspect of C programming, enabling you to interact with external files for data input and output. In this comprehensive guide, we’ll explore the essentials of file handling in C, focusing on reading and writing files. Real-world examples with outputs will illustrate the concepts and help you become proficient in handling files in C.
Introduction to File Handling
File handling in C involves operations such as opening, reading, writing, and closing files. The standard C library provides functions and techniques to perform these operations.
Reading Files
Example: Reading a Text File
#include <stdio.h>
int main() {
FILE *file;
char ch;
// Open a text file for reading
file = fopen("sample.txt", "r");
if (file == NULL) {
printf("File not found or unable to open.\n");
return 1;
}
// Read and print the contents character by character
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
// Close the file
fclose(file);
return 0;
}
Output (assuming “sample.txt” contains “Hello, World!”):
Hello, World!
Writing Files
Example: Writing to a Text File
#include <stdio.h>
int main() {
FILE *file;
// Open a text file for writing
file = fopen("output.txt", "w");
if (file == NULL) {
printf("Unable to create or open the file.\n");
return 1;
}
// Write data to the file
fprintf(file, "This is a sample text written to a file.\n");
// Close the file
fclose(file);
return 0;
}
After running this program, a file named “output.txt” will be created with the specified text.
File handling is essential for tasks such as:
- Reading and processing data from external sources (e.g., input files).
- Storing and retrieving program configurations.
- Logging and error reporting in applications.