C File Handling
With file handling a program can save data in a file, so the data stays after the program ends. In C we use a FILE pointer and the functions of stdio.h.
Steps
- Open the file with
fopen(). - Read or write.
- Close the file with
fclose().
File modes
| Mode | Meaning |
|---|---|
"r" | Read. The file must exist. |
"w" | Write. Creates the file, or erases the old content. |
"a" | Append. Adds at the end of the file. |
"r+" | Read and write. The file must exist. |
"w+" | Read and write. Erases the old content. |
"a+" | Read and append. |
Add b for binary files, like "rb" or "wb".
Write to a file
#include <stdio.h>
int main(void) {
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("Cannot open the file\n");
return 1;
}
fprintf(fp, "Robin 85\n");
fprintf(fp, "Maria 92\n");
fclose(fp);
printf("File written\n");
return 0;
}
Output:
Output of the above program is
File written
The file students.txt is now created in the same folder, with two lines.
Append to a file
#include <stdio.h>
int main(void) {
FILE *fp = fopen("students.txt", "a");
if (fp == NULL) return 1;
fputs("John 78\n", fp);
fclose(fp);
printf("Line added\n");
return 0;
}
Output:
Output of the above program is
Line added
Check if a file exists
#include <stdio.h>
int main(void) {
FILE *fp = fopen("missing.txt", "r");
if (fp == NULL) {
printf("File not found\n");
} else {
fclose(fp);
}
return 0;
}
Output:
Output of the above program is
File not found
Note:
Always check if fopen() returned NULL, and always call fclose(). If you forget it, some data may not be saved. Opening a file in "w" mode deletes the old content, so be careful.
Next: C Read From a File.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |