Master C file handling using fopen, fclose, fprintf, fscanf, fgets, and binary operations with fread and fwrite. Complete runnable examples.
Introduction to File Handling in C
Standard C programs store data in volatile RAM, which is lost when the program terminates. File handling allows programs to persist records to secondary disk storage via file streams defined in <stdio.h>.
In C, files are manipulated using the FILE stream pointer type.
File Opening Modes
| Mode | Description | If File Exists | If File Missing |
|---|---|---|---|
"r" | Open for reading | Starts at beginning | Returns NULL |
"w" | Open for writing | Overwrites / truncates | Creates new file |
"a" | Open for appending | Appends to end | Creates new file |
"rb" / "wb" | Binary read / write | Binary stream | Same as text |
Writing to a Text File
Use fopen(), fprintf(), and fclose() to write structured text to disk:
c (ISO Standard)#include <stdio.h> int main() { FILE *file = fopen("output.txt", "w"); if (file == NULL) { printf("Error opening file for writing!\n"); return 1; } fprintf(file, "C Programming File Handling\n"); fprintf(file, "Persistent data line 2: %d\n", 42); fclose(file); printf("File written successfully!\n"); return 0; }
Reading from a File (fgets)
Always verify that fopen() does not return NULL before reading:
c (ISO Standard)#include <stdio.h> int main() { FILE *file = fopen("output.txt", "r"); char buffer[256]; if (file == NULL) { printf("Unable to open file for reading.\n"); return 1; } while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("Read: %s", buffer); } fclose(file); return 0; }
Binary File I/O (fwrite & fread)
Binary operations allow reading and writing complete memory structs directly to disk:
c (ISO Standard)#include <stdio.h> typedef struct { int id; double balance; } Account; int main() { Account acc = {101, 1540.50}; FILE *file = fopen("account.bin", "wb"); if (file != NULL) { fwrite(&acc, sizeof(Account), 1, file); fclose(file); printf("Account struct saved in binary format.\n"); } return 0; }
Related C Tutorials
- Group data records with Structures in C Programming.
- Review pointer references and stream management in Pointers in C Guide.
- Explore the entire Tutorials Curriculum.