Chapter 14: File Handling
This is one of the most important and practical topics in C programming. Until now, all our data was lost when the program ended. With file handling, we can save data permanently on the hard disk and read it back anytime – even after closing the program.
C provides powerful functions to work with files:
- Open a file
- Read from it
- Write to it
- Close it
- Move around inside it (random access)
All file handling functions are declared in <stdio.h> header.
1. Opening and Closing Files
Opening a file:
|
0 1 2 3 4 5 6 |
FILE *file_pointer = fopen("filename", "mode"); |
- FILE * is a special pointer type for files
- fopen() returns NULL if file cannot be opened
Common Modes:
| Mode | Meaning | Creates file if not exist? | Starts from |
|---|---|---|---|
| “r” | Read only | No | Beginning |
| “w” | Write only (overwrites if exists) | Yes | Beginning |
| “a” | Append (add at end) | Yes | End |
| “r+” | Read + Write | No | Beginning |
| “w+” | Read + Write (overwrites) | Yes | Beginning |
| “a+” | Read + Append | Yes | End |
Closing a file:
|
0 1 2 3 4 5 6 |
fclose(file_pointer); |
Always close files when you’re done – otherwise data may be lost or file may get corrupted.
Example – Open and Close a File
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <stdio.h> int main() { FILE *fp; // Open file for writing fp = fopen("myfile.txt", "w"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } printf("File opened successfully.\n"); // Close the file fclose(fp); printf("File closed.\n"); return 0; } |
2. Writing to Files
fprintf() – Like printf(), but writes to file
fputs() – Writes a string to file
Example – Write some data to file
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <stdio.h> int main() { FILE *fp; fp = fopen("student.txt", "w"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Writing using fprintf() fprintf(fp, "Student Name: Alex\n"); fprintf(fp, "Roll Number: 101\n"); fprintf(fp, "Marks: 92.5\n"); // Writing using fputs() fputs("This is line using fputs()\n", fp); fclose(fp); printf("Data written to file successfully.\n"); return 0; } |
Output on screen:
|
0 1 2 3 4 5 6 |
Data written to file successfully. |
Inside student.txt file:
|
0 1 2 3 4 5 6 7 8 9 |
Student Name: Alex Roll Number: 101 Marks: 92.5 This is line using fputs() |
3. Reading from Files
fscanf() – Like scanf(), but reads from file fgets() – Reads a whole line (including spaces)
Example – Read data from file
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> int main() { FILE *fp; char name[50]; int roll; float marks; char line[100]; fp = fopen("student.txt", "r"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Reading using fscanf() fscanf(fp, "%*s %*s %s", name); // Skip "Student Name:" fscanf(fp, "%*s %*s %d", &roll); // Skip "Roll Number:" fscanf(fp, "%*s %*s %f", &marks); // Skip "Marks:" printf("Name: %s\n", name); printf("Roll Number: %d\n", roll); printf("Marks: %.2f\n", marks); // Reading whole line using fgets() fgets(line, 100, fp); printf("Next line: %s", line); fclose(fp); return 0; } |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
Name: Alex Roll Number: 101 Marks: 92.50 Next line: This is line using fputs() |
4. Random Access Files (fseek, ftell)
ftell() – Returns current position in file (in bytes) fseek() – Moves file pointer to any position
Syntax of fseek():
|
0 1 2 3 4 5 6 |
fseek(file_pointer, offset, whence); |
- whence:
- SEEK_SET → from beginning
- SEEK_CUR → from current position
- SEEK_END → from end
Example – Read specific line or move around
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <stdio.h> int main() { FILE *fp; char ch; fp = fopen("student.txt", "r"); if (fp == NULL) { printf("Error opening file!\n"); return 1; } // Move to 10th byte from beginning fseek(fp, 10, SEEK_SET); printf("Position after fseek(10, SEEK_SET): %ld\n", ftell(fp)); // Read character by character from there printf("Characters from 10th byte: "); while ((ch = fgetc(fp)) != EOF) { printf("%c", ch); } printf("\n"); // Go to end and find size of file fseek(fp, 0, SEEK_END); printf("Size of file: %ld bytes\n", ftell(fp)); fclose(fp); return 0; } |
5. Best Practices & Important Tips
- Always check if fopen() returned NULL
- Always fclose() when done
- Use “rb” / “wb” for binary files (images, executables)
- Don’t forget to include <stdio.h>
- Use fgets() instead of gets() – safer (no buffer overflow)
- For large files, use buffering or read in chunks
Today’s Homework
- Write a program that takes student details (name, roll, marks) from user and writes them to a file.
- Write a program that reads the file created above and prints the student details in a nice format.
- Create a program that appends new student data to the existing file (use mode “a”).
- Write a program that counts how many lines are there in a text file (use fgets() in a loop).
- Create a program that copies content from one file to another (character by character or line by line).
