03. Binary File I/O (fread & fwrite) in C
🟡 Difficulty: Intermediate | Direct RAM Struct Persistence, Binary Streams & Record Reading
📖 Definition
Binary file I/O writes and reads raw memory byte blocks directly to and from disk files without performing text character conversions. In C, fwrite() copies raw RAM bytes from a buffer into a file stream, and fread() reads raw bytes from a file stream directly into a destination memory buffer.
🎯 Why It Is Used
- Direct Struct Persistence: Saving and loading complex C structures (or arrays of structures) directly to disk in a single instruction without text formatting overhead.
- High Performance & Compact Disk Size: Binary files are faster to process and consume significantly less disk space than formatted text files.
- Media & Database Storage: Reading image files (JPEG/PNG), audio streams, and database record files.
⚙️ How It Works: Binary Mode Flags ("wb" / "rb")
When working with binary files, open streams using binary mode flags (e.g. "wb" for writing, "rb" for reading, "ab" for appending). On Windows systems, binary mode prevents automatic conversion between \n and \r\n newline pairs, ensuring byte-exact binary fidelity.
📝 Syntax
#include <stdio.h>
// 1. Writing Raw Binary Blocks
size_t written = fwrite(const void *buffer, size_t elem_size, size_t count, FILE *stream);
// 2. Reading Raw Binary Blocks
size_t read_count = fread(void *buffer, size_t elem_size, size_t count, FILE *stream);
// Both functions return the TOTAL COUNT of items successfully processed (NOT total bytes)!
🔀 Text vs Binary File I/O Comparison
| Property | Text File I/O (fprintf / fscanf) |
Binary File I/O (fwrite / fread) |
|---|---|---|
| Disk Storage Format | Human-readable ASCII/UTF-8 characters | Raw unformatted RAM bytes |
| Processing Speed | Slower (Requires text parsing) | Fastest (Direct memory copy) |
| Disk Space Efficiency | Larger (e.g. 123456789 takes 9 bytes) | Compact (4-byte integer) |
| Cross-Platform Portability | High (ASCII text) | Requires endianness consideration |
🌱 Beginner Example: Writing and Reading an Array of Integers
#include <stdio.h>
int main(void) {
int numbers[5] = {100, 200, 300, 400, 500};
// 1. Write raw binary array to disk
FILE *write_fp = fopen("data.bin", "wb");
if (write_fp == NULL) return 1;
size_t items_written = fwrite(numbers, sizeof(int), 5, write_fp);
fclose(write_fp);
printf("Successfully wrote %zu binary items to data.bin\n", items_written);
// 2. Read raw binary array back from disk
int read_buf[5] = {0};
FILE *read_fp = fopen("data.bin", "rb");
if (read_fp == NULL) return 1;
size_t items_read = fread(read_buf, sizeof(int), 5, read_fp);
fclose(read_fp);
printf("Read %zu items back: ", items_read);
for (int i = 0; i < 5; i++) printf("%d ", read_buf[i]);
printf("\n");
return 0;
}
🌼 Intermediate Example: Persisting Struct Records to Binary File
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[32];
double balance;
} Account;
int main(void) {
Account acc1 = {1001, "Satoshi Nakamoto", 500000.00};
// Save struct directly to binary file
FILE *fp_out = fopen("account.dat", "wb");
if (fp_out == NULL) return 1;
fwrite(&acc1, sizeof(Account), 1, fp_out);
fclose(fp_out);
// Read struct back from binary file into fresh variable
Account acc_loaded = {0};
FILE *fp_in = fopen("account.dat", "rb");
if (fp_in == NULL) return 1;
if (fread(&acc_loaded, sizeof(Account), 1, fp_in) == 1) {
printf("=== Loaded Binary Account Record ===\n");
printf("ID : %d\n", acc_loaded.id);
printf("Name : %s\n", acc_loaded.name);
printf("Balance: $%.2lf\n", acc_loaded.balance);
}
fclose(fp_in);
return 0;
}
🌲 Advanced Example: Database File Reader Loop with Record Validation
#include <stdio.h>
typedef struct {
int record_id;
char code[4];
int score;
} Record;
int main(void) {
// Populate binary file with 3 records
Record db[3] = {
{1, "REC1", 95},
{2, "REC2", 88},
{3, "REC3", 92}
};
FILE *out = fopen("records.db", "wb");
if (out != NULL) {
fwrite(db, sizeof(Record), 3, out);
fclose(out);
}
// Read binary records sequentially using fread loop
FILE *in = fopen("records.db", "rb");
if (in == NULL) return 1;
Record temp;
int count = 0;
printf("=== Reading Binary Database Records ===\n");
while (fread(&temp, sizeof(Record), 1, in) == 1) {
printf("Record #%d | ID: %d | Code: %s | Score: %d\n",
++count, temp.record_id, temp.code, temp.score);
}
fclose(in);
return 0;
}
🔍 Line-by-Line Explanation
fopen("data.bin", "wb");: Opens binary stream for writing, bypassing newline translation.fwrite(numbers, sizeof(int), 5, write_fp);: Writes 5 integer items (20 bytes total) fromnumbersto file.while (fread(&temp, sizeof(Record), 1, in) == 1): Loops whilefread()successfully reads 1 fullRecordstruct from the stream.
💻 Expected Terminal Output
Successfully wrote 5 binary items to data.bin
Read 5 items back: 100 200 300 400 500
=== Loaded Binary Account Record ===
ID : 1001
Name : Satoshi Nakamoto
Balance: $500000.00
=== Reading Binary Database Records ===
Record #1 | ID: 1 | Code: REC1 | Score: 95
Record #2 | ID: 2 | Code: REC2 | Score: 88
Record #3 | ID: 3 | Code: REC3 | Score: 92
⚠️ Common Mistakes & Pitfalls
- Forgetting Binary Mode Flag (
"rb"/"wb"): Opening binary files in text mode ("r"/"w") on Windows causes premature EOF detection if binary byte value0x1A(CTRL+Z) is encountered! - Writing Structs Containing Pointers: Calling
fwrite()on a struct containing pointer members (e.g.char *name) writes RAM pointer addresses to disk rather than the string text! When reloaded later, the pointers point to invalid addresses (Segmentation Fault).
📌 Important Rules & Limitations
- Always open binary files using binary modes (
"rb","wb","ab"). - Do not write structs containing raw pointer members to binary files. Convert pointers to fixed char arrays or serialize fields individually.
- Check that
fread()andfwrite()return counts match the requested item count.
🌐 Multilingual Explanation: English
Binary I/O (fwrite / fread) writes and reads raw RAM byte blocks directly. Always use binary mode flags ("rb", "wb") and never persist structs containing raw pointer members.
🌐 Multilingual Explanation: Hindi (Roman Script)
Binary I/O RAM ke raw bytes ko seedhe disk par save karta hai. Mode mein "wb" aur "rb" lagayein. Pointer members wale structs ko seedhe fwrite mat karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
Binary I/O RAM chya raw bytes la direct file madhye write karto (fwrite / fread). Binary files sathi "rb" aani "wb" mode vapra.
❓ Practice Questions
- Why does calling
fwrite()on a struct containing achar *namepointer member cause bugs when reading the file back later? - What is the difference between opening a file in
"w"mode versus"wb"mode on Windows? - What value does
fread()return if requested to read 5 items, but only 2 remain in the file?
🚀 Practical Coding Challenge
Write a C program named binary_student_db.c that allows the user to append student records (ID, name, marks) to a binary file students.bin and read all records back using an fread loop.
🧭 Navigation & Breadcrumbs
← Previous: 02. Formatted Text I/O | Module 16 Guide | Next: 04. Random Access File Seeking →