Binary Files in C
Saving a structure to a text file means printing every field with fprintf and parsing it back with fscanf. With a binary file, you can save the whole structure in one call, exactly as it sits in memory, and read it back just as easily.
In this lesson you will use fwrite() and fread() to store arrays and student records, read them back, search for a record, and compare binary and text file sizes.
What You Will Learn
- What a binary file stores.
- The syntax of fwrite and fread.
- How to save and load an array.
- How to save and load structures (records).
- How to read records one by one until the end.
- Advantages and limits of binary files.
Binary Files Explained
Exam definition: A binary file stores data as raw bytes, exactly as it is represented in memory. fwrite(ptr, size, count, fp) writes count items of size bytes from memory to the file; fread(ptr, size, count, fp) reads them back. Both return the number of items actually written or read.
Memory trick: A text file is like writing a letter describing your furniture ("one table, 4 legs…"); someone must read and rebuild it. A binary file is like packing the furniture itself in a box: fwrite packs it, fread unpacks it, no rebuilding needed. But only someone with the same kind of house (same system) can unpack it correctly.
Syntax of fwrite() and fread()
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *fp);
size_t fread (void *ptr, size_t size, size_t count, FILE *fp);
FILE *fp = fopen("data.bin", "wb"); /* "b" for binary */
fwrite(&s, sizeof s, 1, fp); /* one structure */
fwrite(arr, sizeof arr[0], n, fp); /* n array elements */
fp = fopen("data.bin", "rb");
fread(&s, sizeof s, 1, fp); /* returns 1 if read, 0 at end */
| Argument | Meaning |
|---|---|
ptr | Address of the data in memory (&var or array name) |
size | Size of one item in bytes (use sizeof) |
count | How many items |
fp | File opened in a binary mode |
| Return | Items actually written/read (less than count = end or error) |
Example 1: Save an Array, Load It Back, Compare File Sizes
#include <stdio.h>
long file_size(const char *name)
{
long size;
FILE *fp = fopen(name, "rb");
if (fp == NULL)
return -1;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fclose(fp);
return size;
}
int main(void)
{
int marks[5] = {1234567, 2345678, 3456789, 4567890, 5678901};
int loaded[5];
size_t got;
int i;
FILE *fp;
fp = fopen("marks.bin", "wb");
if (fp == NULL)
return 1;
fwrite(marks, sizeof marks[0], 5, fp); /* all 5 in one call */
fclose(fp);
fp = fopen("marks.txt", "w");
if (fp == NULL)
return 1;
for (i = 0; i < 5; i++)
fprintf(fp, "%d\n", marks[i]);
fclose(fp);
fp = fopen("marks.bin", "rb");
if (fp == NULL)
return 1;
got = fread(loaded, sizeof loaded[0], 5, fp);
fclose(fp);
printf("Read %zu numbers:", got);
for (i = 0; i < 5; i++)
printf(" %d", loaded[i]);
printf("\n");
printf("Binary file: %ld bytes, text file: %ld bytes\n",
file_size("marks.bin"), file_size("marks.txt"));
remove("marks.bin");
remove("marks.txt");
return 0;
}
Output
Read 5 numbers: 1234567 2345678 3456789 4567890 5678901 Binary file: 20 bytes, text file: 40 bytes
Code Explanation
fwrite(marks, sizeof marks[0], 5, fp)writes 5 items of 4 bytes: 20 bytes straight from memory.- The text file stores each number as 7 digit characters plus
'\n': 8 × 5 = 40 bytes. Binary is smaller for big numbers. freadfillsloadeddirectly and returns 5, the number of items read.file_sizejumps to the end withfseekand asks the position withftell(next lesson).
How Records Are Stored in a Binary File
struct student { int roll; char name[20]; float cgpa; }; sizeof = 28 bytes
file: [ record 0: 28 bytes ][ record 1: 28 bytes ][ record 2: 28 bytes ]
byte 0 byte 28 byte 56 total 84
Record k starts at byte k * sizeof(struct student) -> easy random access
Because every record has the same size, you can jump straight to record k. That's why databases and games use binary records.
Example 2: Store Student Records and Search by Roll Number
#include <stdio.h>
struct student
{
int roll;
char name[20];
float cgpa;
};
int main(void)
{
struct student batch[3] = { {101, "Asha", 8.7f}, {102, "Ravi", 7.2f}, {103, "Neha", 9.4f} };
struct student s;
FILE *fp;
int key = 102, found = 0;
fp = fopen("students.dat", "wb");
if (fp == NULL)
return 1;
fwrite(batch, sizeof batch[0], 3, fp);
fclose(fp);
fp = fopen("students.dat", "ab"); /* append one more */
if (fp == NULL)
return 1;
s.roll = 104;
sprintf(s.name, "%s", "Arjun");
s.cgpa = 6.9f;
fwrite(&s, sizeof s, 1, fp);
fclose(fp);
fp = fopen("students.dat", "rb");
if (fp == NULL)
return 1;
printf("All records:\n");
while (fread(&s, sizeof s, 1, fp) == 1) /* one record at a time */
{
printf(" %d %-6s %.1f\n", s.roll, s.name, s.cgpa);
if (s.roll == key)
found = 1;
}
fclose(fp);
printf("Roll %d %s\n", key, found ? "found" : "not found");
printf("Each record = %zu bytes\n", sizeof s);
remove("students.dat");
return 0;
}
Output
All records: 101 Asha 8.7 102 Ravi 7.2 103 Neha 9.4 104 Arjun 6.9 Roll 102 found Each record = 28 bytes
- The whole array of 3 structures is written with one fwrite call.
"ab"appends a 4th record at the end without touching the others.while (fread(&s, sizeof s, 1, fp) == 1)reads records until fread returns 0 at the end of the file. This is the standard loop for binary records.
Advantages and Limitations of Binary Files
| Advantages | Limitations |
|---|---|
| Whole structures in one call | Not readable in a text editor |
| Usually smaller (numbers stay as raw bytes) | Depends on the system: int size, byte order, padding |
| Faster: no conversion to text | Pointers inside structures are meaningless when saved |
| Fixed-size records allow random access | A wrong sizeof corrupts all records after it |
Never save a structure that contains pointers (like char *name): the file would store the address, not the text, and the address is useless next time.
Important Points to Remember
- Open binary files with "rb", "wb", "ab" (and + versions).
- fwrite(ptr, size, count, fp) / fread(ptr, size, count, fp).
- Both return the number of items, not bytes.
- Read records with while (fread(&s, sizeof s, 1, fp) == 1).
- Record k starts at k × sizeof(record).
- Don't store pointers; binary files may not move between different systems.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
fwrite(s, ...) for a single struct | Compile error (needs an address) | fwrite(&s, sizeof s, 1, fp) |
| Swapping size and count arguments | Wrong return value checks | (ptr, sizeof item, count, fp) |
| Opening with "r"/"w" on Windows | Bytes 10/13 get changed: corrupted data | Use "rb"/"wb" |
Saving a struct with char * members | Only addresses saved | Use char name[20] |
| Writing with one struct layout, reading with another | Garbage fields | Keep the same definition |
Binary Files Practice Questions
- What are the four arguments of fwrite?
- What does fread return at the end of the file?
- Why is a binary file usually smaller than a text file for numbers?
- At which byte does record 5 start if each record is 40 bytes?
- Why shouldn't a structure with pointer members be written to a binary file?
Show answers
- Pointer to data, size of one item, number of items, file pointer.
- A value less than requested (0 when no item is read).
- Numbers are stored in their fixed in-memory size (e.g. 4 bytes for an int) instead of one byte per digit plus separators.
- 5 × 40 = byte 200.
- Only the addresses are saved, not the data they point to, and those addresses are invalid later.
Coding Exercise
Write 5 floats (temperatures 31.5, 29.0, 33.2, 35.8, 30.1) to temps.bin with one fwrite, then read them back one at a time with fread and print the highest.
Show solution
#include <stdio.h>
int main(void)
{
float t[5] = {31.5f, 29.0f, 33.2f, 35.8f, 30.1f};
float x, max = -1000;
FILE *fp = fopen("temps.bin", "wb");
if (fp == NULL)
return 1;
fwrite(t, sizeof t[0], 5, fp);
fclose(fp);
fp = fopen("temps.bin", "rb");
if (fp == NULL)
return 1;
while (fread(&x, sizeof x, 1, fp) == 1)
if (x > max)
max = x;
fclose(fp);
printf("Highest: %.1f\n", max);
remove("temps.bin");
return 0;
}
Highest: 35.8
Quick Quiz: Binary Files (MCQ)
-
Function to write a structure to a binary file:
A)
fprintfB)fwriteC)fputsD)fputc -
Mode to open a binary file for reading:
A)
"r"B)"rb"C)"br"D)"read" -
fread returns:
A) Bytes read B) Items read C) Always 1 D) A pointer
-
Correct call to write one
struct student s:A)
fwrite(s, 1, sizeof s, fp)B)fwrite(&s, sizeof s, 1, fp)C)fwrite(fp, &s)D)fwrite(&s, fp) -
Binary files are:
A) Always readable in Notepad B) Stored as raw bytes C) Only for images D) Slower than text
Show answers
- B:
fwrite. - B:
"rb". - B: items read.
- B.
- B: raw bytes.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Binary file | Stores raw bytes as in memory |
|---|---|
| Modes | rb, wb, ab (+ versions) |
| Write | fwrite(ptr, size, count, fp) |
| Read | fread(ptr, size, count, fp) |
| Return value | Items written/read |
| Record loop | while (fread(&s, sizeof s, 1, fp) == 1) |
| Record k offset | k × sizeof(record) |
Frequently asked questions
- What is the difference between fwrite and fprintf?
- fwrite writes raw bytes (binary); fprintf writes formatted text.
- How do you write a structure to a file in C?
- Open in "wb" and call fwrite(&s, sizeof s, 1, fp).
- Why use binary files?
- They are faster, often smaller, store whole records at once and allow random access.
Remember
- Binary = pack the furniture itself.
- fwrite/fread: (where, size of one, how many, file).
Next Topic
Next lesson: Random Access in Files (fseek). You will jump to any position in a file with fseek(), ftell() and rewind().