File Handling in C
File handling allows you to store and access data permanently on disk. Unlike variables (which lose their values when the program ends), a file retains its contents even after the program closes.Steps in File Handling
- Declare a file pointer
- Open the file
- Perform read/write operations
- Close the file
File Opening Modes
| Mode | Description |
|---|---|
"r" | Read — file must already exist |
"w" | Write — creates new file, or overwrites existing |
"a" | Append — adds data at the end of the file |
"r+" | Read + Write — file must exist |
"w+" | Read + Write — creates new or clears existing |
"a+" | Read + Append — read anywhere, write at end only |
Common File Functions
| Function | Purpose |
|---|---|
fopen() | Open a file |
fclose() | Close a file |
fprintf() | Write formatted data |
fscanf() | Read formatted data |
fputc() | Write a single character |
fgetc() | Read a single character |
fputs() | Write a string |
fgets() | Read a string (line by line) |
feof() | Check if end of file is reached |
Writing to a File
Reading from a File
Appending to a File
Checking for NULL
Always check iffopen() returned NULL — it means the file could not be opened (wrong path, no permissions, etc.):