Module 9: File Handling in C
Learning Objectives
By the end of this module, you will be able to:
- Understand what file handling is and why it is important.
- Open and close files using
fopen()andfclose(). - Read and write text files.
- Read and write binary files.
- Use
fprintf(),fscanf(),fread(), andfwrite(). - Handle file errors safely.
- Build practical applications using file handling.
Introduction
When a C program ends, all data stored in variables is lost because it resides in RAM (volatile memory).
Suppose you create a student management system. If the program closes, all student records disappear.
To store data permanently, we use files.
File handling allows programs to:
- Save data permanently
- Read existing data
- Update records
- Delete records
- Share data between programs
File handling is widely used in:
- Banking software
- Library management
- Student databases
- Hospital management systems
- Inventory systems
- Configuration files
- Log files
What is a File?
A file is a collection of data stored permanently on secondary storage devices such as:
- Hard Disk
- SSD
- USB Drive
- Memory Card
Example files:
1students.txt 2notes.txt 3employees.dat 4records.bin
Types of Files
C mainly supports two types of files.
1. Text Files
Store data as readable characters.
Example
1Name: Ankit 2Age: 23 3Course: C Programming
Advantages
- Human-readable
- Easy to edit
- Useful for reports and logs
Disadvantages
- Larger file size
- Slower processing
2. Binary Files
Store data in binary format.
Advantages
- Faster reading and writing
- Smaller file size
- Efficient storage
Disadvantages
- Not human-readable
- Requires programs to interpret data
File Pointer
In C, every file operation is performed using a file pointer.
Declaration
1FILE *fp;
FILE is a structure defined in the <stdio.h> library.
Opening a File using fopen()
The fopen() function opens a file and returns a pointer to it.
Syntax
1FILE *fp; 2 3fp = fopen("filename", "mode");
Example
1FILE *fp; 2 3fp = fopen("students.txt", "r");
If the file cannot be opened, fopen() returns NULL.
File Modes
| Mode | Description |
|---|---|
"r" | Read existing file |
"w" | Write (creates new file or overwrites existing file) |
"a" | Append data at the end of the file |
"r+" | Read and write |
"w+" | Read and write (overwrites existing content) |
"a+" | Read and append |
"rb" | Read binary |
"wb" | Write binary |
"ab" | Append binary |
Checking Whether a File Opened Successfully
Always verify that fopen() did not return NULL.
Example
1#include <stdio.h> 2 3int main() 4{ 5 FILE *fp = fopen("data.txt", "r"); 6 7 if(fp == NULL) 8 { 9 printf("Unable to open file."); 10 return 1; 11 } 12 13 printf("File opened successfully."); 14 15 fclose(fp); 16 17 return 0; 18}
Closing a File using fclose()
Always close files after use.
Syntax
1fclose(fp);
Example
1FILE *fp = fopen("data.txt", "r"); 2 3/* File operations */ 4 5fclose(fp);
Closing files:
- Saves buffered data
- Frees system resources
- Prevents file corruption
Writing to a Text File using fprintf()
fprintf() works similarly to printf(), but writes formatted output to a file.
Syntax
1fprintf(file_pointer, "format", values);
Example
1#include <stdio.h> 2 3int main() 4{ 5 FILE *fp = fopen("student.txt", "w"); 6 7 if(fp == NULL) 8 return 1; 9 10 fprintf(fp, "Name: Ankit\n"); 11 fprintf(fp, "Marks: 95\n"); 12 13 fclose(fp); 14 15 return 0; 16}
File Content
1Name: Ankit 2Marks: 95
Reading from a Text File using fscanf()
fscanf() reads formatted input from a file.
Example
1#include <stdio.h> 2 3int main() 4{ 5 char name[30]; 6 int marks; 7 8 FILE *fp = fopen("student.txt", "r"); 9 10 if(fp == NULL) 11 return 1; 12 13 fscanf(fp, "Name: %29s\nMarks: %d", name, &marks); 14 15 printf("%s\n", name); 16 printf("%d\n", marks); 17 18 fclose(fp); 19 20 return 0; 21}
Reading a File Line by Line
fgets() is commonly used to read text files safely.
Example
1#include <stdio.h> 2 3int main() 4{ 5 char line[100]; 6 7 FILE *fp = fopen("notes.txt", "r"); 8 9 if(fp == NULL) 10 return 1; 11 12 while(fgets(line, sizeof(line), fp)) 13 { 14 printf("%s", line); 15 } 16 17 fclose(fp); 18 19 return 0; 20}
Writing Binary Files using fwrite()
fwrite() writes binary data directly to a file.
Syntax
1fwrite(pointer, size, count, file_pointer);
Example
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 float marks; 7}; 8 9int main() 10{ 11 struct Student student = {101, 95.5f}; 12 13 FILE *fp = fopen("student.dat", "wb"); 14 15 if(fp == NULL) 16 return 1; 17 18 fwrite(&student, sizeof(student), 1, fp); 19 20 fclose(fp); 21 22 return 0; 23}
Reading Binary Files using fread()
fread() reads binary data from a file.
Syntax
1fread(pointer, size, count, file_pointer);
Example
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 float marks; 7}; 8 9int main() 10{ 11 struct Student student; 12 13 FILE *fp = fopen("student.dat", "rb"); 14 15 if(fp == NULL) 16 return 1; 17 18 fread(&student, sizeof(student), 1, fp); 19 20 printf("%d\n", student.roll); 21 printf("%.2f\n", student.marks); 22 23 fclose(fp); 24 25 return 0; 26}
Output
1101 295.50
Text Files vs Binary Files
| Text Files | Binary Files |
|---|---|
| Human-readable | Not human-readable |
| Larger file size | Smaller file size |
| Slower processing | Faster processing |
| Easier to edit | Difficult to edit manually |
| Best for reports and logs | Best for structured data |
Practice Project 1: Notes Application
1#include <stdio.h> 2 3int main() 4{ 5 FILE *fp; 6 char note[200]; 7 8 fp = fopen("notes.txt", "a"); 9 10 if(fp == NULL) 11 { 12 printf("Unable to open file."); 13 return 1; 14 } 15 16 printf("Write your note:\n"); 17 fgets(note, sizeof(note), stdin); 18 19 fprintf(fp, "%s", note); 20 21 fclose(fp); 22 23 printf("Note saved successfully."); 24 25 return 0; 26}
Practice Project 2: Student Record System
1#include <stdio.h> 2 3struct Student 4{ 5 int roll; 6 char name[30]; 7 float marks; 8}; 9 10int main() 11{ 12 struct Student student; 13 14 FILE *fp = fopen("students.dat", "ab"); 15 16 if(fp == NULL) 17 { 18 printf("Unable to open file."); 19 return 1; 20 } 21 22 printf("Enter Roll Number: "); 23 scanf("%d", &student.roll); 24 25 printf("Enter Name: "); 26 scanf("%29s", student.name); 27 28 printf("Enter Marks: "); 29 scanf("%f", &student.marks); 30 31 fwrite(&student, sizeof(student), 1, fp); 32 33 fclose(fp); 34 35 printf("Student record saved successfully."); 36 37 return 0; 38}
Common File Handling Errors
File Not Found
Occurs when attempting to open a file in read mode that does not exist.
1FILE *fp = fopen("missing.txt", "r");
Always check for NULL.
Forgetting to Close the File
Incorrect
1FILE *fp = fopen("data.txt", "w"); 2 3/* Missing fclose() */
Correct
1fclose(fp);
Reading Beyond the End of a File
Always verify the return value of fscanf(), fgets(), or fread() before using the data.
Incorrect File Mode
Examples
1Open with "r" but try writing. 2Open with "w" when you intended to append. 3Open binary data using text mode.
Choose the correct mode for each operation.
Best Practices
- Always check whether
fopen()returnsNULL. - Close every file using
fclose()after use. - Use
fgets()instead offscanf()for reading lines containing spaces. - Prefer binary files for storing structures and large datasets.
- Use text files for configuration, logs, and reports.
- Handle file errors gracefully and display meaningful error messages.
- Avoid hardcoding file paths when writing portable programs.
Module Summary
In this module, you learned:
- What file handling is and why persistent storage is important.
- The difference between text files and binary files.
- How to use the
FILEpointer withfopen()andfclose(). - How to write formatted text using
fprintf()and read it usingfscanf(). - How to read text safely line by line with
fgets(). - How to store and retrieve binary data using
fwrite()andfread(). - Common file handling errors and best practices for reliable programs.
- How to build practical applications such as a notes application and a student record system.
After completing this module, you'll be ready to learn Preprocessor Directives and Header Files in C, including macros, conditional compilation, header guards, standard libraries, and creating your own reusable header files.