Binary File Handling in C Programming
Binary File Handling in C Programming
Introduction to Binary File Handling in C Programming
Binary file handling in C programming is used to store data in binary format instead of text format. It allows faster data processing and efficient storage.
Binary file handling in C programming is commonly used in applications like databases, games, and system-level programming.
What is a Binary File in C Programming
A binary file stores data in the same format as it is stored in memory. Unlike text files, binary files are not human-readable.
File Modes for Binary Files
Common Binary Modes
"rb"→ Read binary file"wb"→ Write binary file"ab"→ Append binary file"rb+"→ Read and write binary file
Writing to Binary File
Example: Writing Structure to Binary File
struct Student {
int id;
float marks;
};
int main() {
FILE *fp;
struct Student s1 = {1, 85.5};
fp = fopen(“student.dat”, “wb”);
fwrite(&s1, sizeof(s1), 1, fp);
fclose(fp);
return 0;
}
Reading from Binary File
Example: Reading Structure from Binary File
struct Student {
int id;
float marks;
};
int main() {
FILE *fp;
struct Student s1;
fp = fopen(“student.dat”, “rb”);
fread(&s1, sizeof(s1), 1, fp);
printf(“ID: %d\n”, s1.id);
printf(“Marks: %.2f”, s1.marks);
fclose(fp);
return 0;
}
Writing Multiple Records
struct Student {
int id;
};
int main() {
FILE *fp = fopen(“data.dat”, “wb”);
struct Student s[3] = {{1}, {2}, {3}};
fwrite(s, sizeof(struct Student), 3, fp);
fclose(fp);
return 0;
}
Reading Multiple Records
struct Student {
int id;
};
int main() {
FILE *fp = fopen(“data.dat”, “rb”);
struct Student s[3];
fread(s, sizeof(struct Student), 3, fp);
for(int i = 0; i < 3; i++) {
printf(“ID: %d\n”, s[i].id);
}
fclose(fp);
return 0;
}
Difference Between Text and Binary Files
Text Files
- Human-readable
- Slower processing
- Uses formatted I/O
Binary Files
- Not human-readable
- Faster processing
- Uses fread and fwrite
Advantages of Binary File Handling
Key Benefits
- Faster read/write operations
- Efficient storage
- Suitable for large data
- Preserves exact data format
Common Mistakes
Avoid These Errors
- Not using correct file mode
- Mismatch in data size
- Forgetting to close file
- Reading wrong structure format
Best Practices
Tips
- Always check file pointer
- Use correct structure size
- Handle errors properly
- Close file after use
Start Learning C Programming
Practice binary file handling to build advanced and efficient C programming applications.
Summary
Binary file handling in C programming allows fast and efficient data storage using binary format. It is widely used in advanced applications.
FAQs
What is binary file in C programming?
A file that stores data in binary format.
Which functions are used in binary files?
fread() and fwrite().
Why binary files are faster?
Because they store data in raw format.
Can we store structures in binary files?
Yes.



