Binary Files in C
In the previous lessons, you worked with text files where data is stored in human-readable form.
However, text files are slower and take more space.
To store data efficiently and quickly, C uses binary files.
What Is a Binary File?
A binary file stores data in the same format as it is stored in memory.
Binary files:
- Are faster than text files
- Use less storage
- Are not human-readable
Why Use Binary Files?
Binary files are used when:
- Speed is important
- Large data is involved
- Exact memory representation is needed
Examples:
- Student databases
- Game save files
- System logs
Opening a Binary File
Binary files use the same fopen() function, but with binary modes.
rb– Read binarywb– Write binaryab– Append binary
Writing to a Binary File
The fwrite() function is used to write binary data.
#include <stdio.h>
struct Student {
int roll;
float marks;
};
int main() {
FILE *fp;
struct Student s = {101, 85.5};
fp = fopen("student.dat", "wb");
fwrite(&s, sizeof(s), 1, fp);
fclose(fp);
return 0;
}
This program stores the entire structure directly into a file.
Reading from a Binary File
The fread() function reads binary data.
#include <stdio.h>
struct Student {
int roll;
float marks;
};
int main() {
FILE *fp;
struct Student s;
fp = fopen("student.dat", "rb");
fread(&s, sizeof(s), 1, fp);
printf("Roll: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);
fclose(fp);
return 0;
}
The data is read exactly as it was stored.
Important Difference: Text vs Binary
- Text file → Human readable
- Binary file → Machine readable
- Text uses fprintf / fscanf
- Binary uses fwrite / fread
Real-World Analogy
Think of binary files like packing items in a sealed box:
- Fast to pack and unpack
- Compact
- Not readable without opening properly
Mini Practice
- Create a structure for Employee (id, salary)
- Write it into a binary file
- Read and display the data
Quick Quiz
Q1. Which function writes binary data?
fwrite()
Q2. Which function reads binary data?
fread()
Q3. Are binary files human readable?
No.
Q4. Which mode is used to write binary files?
wb
Q5. Are binary files faster than text files?
Yes.