In this tutorial, you'll learn how to read binary data from a binary file and display it on the console using the C programming language. This is the natural companion to Assignment 7 (writing data to a binary file). The program opens the file in read-binary mode, reads one record at a time with fread(), and prints each record's fields. It's the same pattern used by every database, save-game loader, and file-format parser.
📝 Problem Statement
Write a program in C to read binary data from a binary file and display it.
⚙️ How the Program Works
The program follows the standard read lifecycle for binary data:
- Define the struct that matches the record layout written in Assignment 7. Both writer and reader must use the same struct definition.
- Open the file in read-binary mode with
fopen("students.bin", "rb"). - Check for
NULLin case the file is missing. - Read one record at a time with
fread(). The loop ends whenfreadreturns 0 (end of file or read error). - Display each record with
printf(). - Close the file with
fclose().
💻 Complete C Program
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main(void)
{
FILE *fp;
struct Student s;
size_t read_count;
int record_no = 0;
/* Open the binary file in read mode */
fp = fopen("students.bin", "rb");
if (fp == NULL)
{
printf("Error: Could not open students.bin for reading.\n");
return 1;
}
printf("%-6s %-20s %-10s\n", "ID", "Name", "Marks");
printf("--------------------------------------\n");
/* Read one struct at a time until fread returns 0 */
while ((read_count = fread(&s, sizeof(struct Student), 1, fp)) == 1)
{
record_no++;
printf("%-6d %-20s %-10.2f\n", s.id, s.name, s.marks);
}
fclose(fp);
printf("--------------------------------------\n");
printf("Total records read: %d\n", record_no);
return 0;
}🖥️ Sample Output
Assume students.bin was created by the program in Assignment 7 with three records. Running this program:
--------------------------------------
101 Alice 87.50
102 Bob 91.00
103 Carol 78.50
--------------------------------------
Total records read: 3
The fields are aligned with %-6d, %-20s, and %-10.2f to produce a clean table. If the file were empty, the program would print "Total records read: 0" without crashing.
🔍 Line-by-Line Explanation
| Line / Code | Explanation |
|---|---|
struct Student { ... }; |
Must match the struct used when writing the file. A different definition here — same field types, same order — would read garbage. |
fopen("students.bin", "rb") |
Opens for binary reading. The b is essential on Windows; on Linux it's a no-op but still good practice. |
fread(&s, sizeof(struct Student), 1, fp) |
Reads one full struct's worth of bytes into s. Returns the number of items successfully read — 1 on success, 0 at end of file or on error. |
while (... == 1) |
Continues the loop as long as a full record was read. When fread returns 0, the loop exits. |
printf("%-6d %-20s %-10.2f\n", ...) |
Left-aligned columns with fixed widths. %-6d = ID, %-20s = name, %-10.2f = marks with two decimal places. |
fclose(fp) |
Releases the file handle. |
fread(...) == 1, not != 0. Both work, but == 1 makes it explicit that we want exactly one full record per iteration. If the file is truncated mid-record, fread returns 0 and we stop — avoiding reading a partial struct.
📂 Reading Binary vs Reading Text
It's worth understanding how binary reading differs from text reading, since both use the same FILE * handle:
| Aspect | Text mode ("r") |
Binary mode ("rb") |
|---|---|---|
| Read function | fgets, fgetc, fscanf |
fread |
| Line ending translation | On Windows, \r\n → \n |
None — bytes are read as-is |
| End of file marker | EOF may be triggered by Ctrl+Z |
Only true EOF from the OS |
| Struct reading | Not possible (no fscanf for raw structs) |
Direct with fread |
🐛 Common Pitfalls
- Struct layout mismatch: If you change the struct (add a field, reorder fields, change a type) after writing the file, the reader will misinterpret the bytes.
- Missing
bin the mode: On Windows, opening a binary file with"r"may corrupt the data by translating line endings. - Ignoring
fread's return value: Iffreadreturns less than 1, either the file ended or an error occurred. You should checkfeof(fp)andferror(fp)to distinguish the two. - Reading a file written on a different platform: Endianness and struct padding may differ. For portable files, serialize fields one by one.
- Reading past the end of the file: The loop condition
fread(...) == 1handles this — a partial read returns 0 and the loop exits.
💡 Tips & Best Practices
- Use
feof(fp)andferror(fp)after the loop to distinguish a normal end of file from a read error. - Store a "magic number" or version byte at the start of the file so the reader can detect format mismatches early.
- Use
sizeof(struct YourStruct)rather than a hard-coded byte count — the struct layout can change between builds. - Compile with
gcc -Wall -Wextra -std=c11 -gto catch type mismatches. - If the file contains many records, you can read them all at once with
fread(array, sizeof(struct Student), N, fp)— but you need to know N in advance.