C File Handling
C file handling lets your programs save data to disk and read it back later. All file work goes through a FILE pointer returned by fopen, and every opened file must be closed with fclose.
fopen Modes
- "r": read an existing file
- "w": write; creates the file or erases an existing one
- "a": append to the end; creates the file if needed
- "r+", "w+", "a+": read and write variants
- Add "b" (for example "rb") for binary files.
Writing to a File
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "w");
if (fp == NULL) {
perror("Could not open file");
return 1;
}
fprintf(fp, "Line 1: learn C\n");
fprintf(fp, "Line 2: practice daily\n");
fclose(fp);
printf("File saved\n");
return 0;
}File saved
Reading a File Line by Line
fgets returns NULL when it reaches the end of the file, which makes it perfect as a loop condition.
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "r");
if (!fp) {
perror("notes.txt");
return 1;
}
char line[100];
int n = 1;
while (fgets(line, sizeof line, fp) != NULL) {
printf("%d> %s", n++, line);
}
fclose(fp);
return 0;
}1> Line 1: learn C 2> Line 2: practice daily
Appending Data
#include <stdio.h>
int main(void) {
FILE *fp = fopen("notes.txt", "a");
if (!fp) return 1;
fputs("Line 3: build projects\n", fp);
fclose(fp);
printf("Appended one line\n");
return 0;
}Appended one line
Error Handling Tips
Always check that fopen did not return NULL; the file may not exist or you may lack permission. perror prints your message followed by the system's reason, such as "No such file or directory". Close every file you open so data is flushed to disk.
Frequently asked questions
How do I check if a file exists in C?
Try to open it with fopen(name, "r"). If it returns NULL, the file does not exist or cannot be read. Close it if it opened successfully.
What is the difference between "w" and "a" modes?
"w" erases the file and starts empty, while "a" keeps existing contents and adds new data at the end.
Why should I call fclose in C?
fclose flushes buffered data to disk and releases the file handle. Forgetting it can lose data and, in large programs, run out of file handles.