ile handling in C allows your program to store data permanently on a hard drive. Without it, all your variables and data disappear the moment the program closes.
In C, we use a special pointer type called FILE * to interact with files.
The Basic Workflow
Open the file using
fopen().Check if the file actually opened (don't skip this!).
Process (Read from or Write to) the file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fptr;
char content[100];
// --- WRITING TO A FILE ---
fptr = fopen("example.txt", "w");
if (fptr == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(fptr, "Hello, C File Handling!");
fclose(fptr); // Always close after writing
printf("Data written successfully.\n");
// --- READING FROM A FILE ---
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
// fgets reads a string until it hits a newline or the limit
if (fgets(content, 100, fptr) != NULL) {
printf("Content of file: %s\n", content);
}
fclose(fptr); // Always close after reading
return 0;
}Expected Output:
Data written successfully.
Content of file: Hello, C File Handling!ModeMeaningDescription"w"WriteCreates a new file (or overwrites an existing one)."r"ReadOpens an existing file to read data."a"AppendAdds new data to the end of an existing file.
Pro-Tips for File Handling
The "NULL" Check: Always check if your
FILE *isNULL. If you try to write to aNULLpointer (e.g., if the file is locked or the disk is full), your program will crash.