Read Binary Data from a File — C File Handling Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Read Binary Data from a Binary File and Display It

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.

C program to read binary data from a binary file and display it using fopen rb mode and fread, with step-by-step explanation.

📝 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:

  1. Define the struct that matches the record layout written in Assignment 7. Both writer and reader must use the same struct definition.
  2. Open the file in read-binary mode with fopen("students.bin", "rb").
  3. Check for NULL in case the file is missing.
  4. Read one record at a time with fread(). The loop ends when fread returns 0 (end of file or read error).
  5. Display each record with printf().
  6. 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:

Console: ID Name Marks
--------------------------------------
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.
⚠️ Important: The loop condition is 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 b in the mode: On Windows, opening a binary file with "r" may corrupt the data by translating line endings.
  • Ignoring fread's return value: If fread returns less than 1, either the file ended or an error occurred. You should check feof(fp) and ferror(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(...) == 1 handles this — a partial read returns 0 and the loop exits.

💡 Tips & Best Practices

  • Use feof(fp) and ferror(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 -g to 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.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 7. Write Data to a Binary File
  • 3. Append Data to an Existing Binary File
  • 16. Store and Retrieve Student Records Using Structures and Binary Files
  • Binary Files in C — Overview
  • Files FAQ

Previous Problem: -->> 7. Write Data to a Binary File   ||   Next Problem: -->> 9. Merge Multiple Text Files into a Single Text File

Back to Index: -->> File Handling Assignments in C


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.