Store & Retrieve Student Records — C Binary File Solution
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Store and Retrieve Student Records Using Structures and Binary Files

In this tutorial, you'll learn how to store and retrieve student records using structures and binary files in C with fwrite() and fread(). This is the most practical combination of C features you'll encounter: structures organize related data, and binary files persist that data efficiently across program runs. The same pattern — write an array of records with fwrite, then read them back with fread — underlies everything from simple student databases to game save files, configuration stores, and small record-management utilities.

C program to store and retrieve student records using structures and binary files with fwrite and fread, with step-by-step explanation.

📝 Problem Statement

Write a program in C to store and retrieve student records using structures and binary files (fwrite/fread).

⚙️ How the Program Works

The program has two phases: a write phase that serializes an array of structs to disk, and a read phase that reconstructs them in memory.

  1. Define the struct — a Student with id, name, and marks.
  2. Fill an array of Student records (or read them from user input).
  3. Open the file in binary write mode ("wb").
  4. Write each record with fwrite(&students[i], sizeof(struct Student), 1, fp).
  5. Close the file so all records reach disk.
  6. Reopen the file in binary read mode ("rb").
  7. Read each record with fread(&s, sizeof(struct Student), 1, fp) until it returns 0.
  8. Display each record to verify the round-trip.

💻 Complete C Program

#include <stdio.h> #include <stdlib.h> struct Student { int id; char name[50]; float marks; }; int main(void) { FILE *fp; struct Student students[3] = { { 101, "Alice", 87.5f }, { 102, "Bob", 91.0f }, { 103, "Carol", 78.5f } }; struct Student s; int i; /* ---- PHASE 1: WRITE RECORDS ---- */ fp = fopen("students.bin", "wb"); if (fp == NULL) { printf("Error: Could not open 'students.bin' for writing.\n"); return 1; } for (i = 0; i < 3; i++) { if (fwrite(&students[i], sizeof(struct Student), 1, fp) != 1) { printf("Error: Failed to write record %d.\n", i + 1); fclose(fp); return 1; } } fclose(fp); printf("3 records written to students.bin.\n\n"); /* ---- PHASE 2: READ RECORDS BACK ---- */ 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"); while (fread(&s, sizeof(struct Student), 1, fp) == 1) { printf("%-6d %-20s %-10.2f\n", s.id, s.name, s.marks); } fclose(fp); return 0; }

🖥️ Sample Output

Console: 3 records written to students.bin.

ID Name Marks
--------------------------------------
101 Alice 87.50
102 Bob 91.00
103 Carol 78.50

The file students.bin now contains three Student records back-to-back. On a typical 64-bit Linux system, each record is 60 bytes (4 bytes for id, 50 for name, 4 for marks, plus padding), so the file is around 180 bytes. Its content is unreadable in a text editor because the bytes are the raw in-memory representation of the structs.

🔍 Line-by-Line Explanation

Line / Code Explanation
struct Student { ... }; Defines the record layout. Both the writer and the reader must use the same struct.
struct Student students[3] = { ... }; Initializes three records. In a real program you'd fill these from user input or a CSV file.
fopen("students.bin", "wb") Opens for binary writing. Creates the file or truncates it if it exists.
fwrite(&students[i], sizeof(struct Student), 1, fp) Writes one full struct (its entire byte size) to the file. The first argument is the address, the second is the element size, the third is the count, and the fourth is the file pointer.
if (fwrite(...) != 1) Checks the write succeeded. fwrite returns the number of items successfully written.
fopen("students.bin", "rb") Reopens for reading in binary mode. Same filename, different mode.
while (fread(&s, sizeof(struct Student), 1, fp) == 1) Reads one full struct per iteration. Stops at end of file (or on a partial read).
printf("%-6d %-20s %-10.2f\n", ...) Displays each record in a clean table with left-aligned columns.
⚠️ Important: The struct that writes the file and the struct that reads it must be byte-for-byte identical. If you add a field, reorder fields, or change a type after the file has been written, the reader will misinterpret the data. Include a version byte at the start of the file if you plan to evolve the format.

🔁 Separating Write and Read Phases

In practice you rarely write and read in the same program run — you write in one program (data entry) and read in another (reporting). Each phase is a self-contained function that follows the same pattern:

/* Write N records to a binary file. Returns 0 on success. */ int save_students(const char *filename, const struct Student *arr, int n) { FILE *fp = fopen(filename, "wb"); if (!fp) return -1; size_t written = fwrite(arr, sizeof(struct Student), n, fp); fclose(fp); return (written == (size_t)n) ? 0 : -1; } /* Read all records from a binary file. Returns the number of records read. */ int load_students(const char *filename, struct Student *arr, int max_records) { FILE *fp = fopen(filename, "rb"); if (!fp) return -1; int count = 0; while (count < max_records && fread(&arr[count], sizeof(struct Student), 1, fp) == 1) { count++; } fclose(fp); return count; }

Note that save_students calls fwrite with the whole array at once (arr, n) rather than looping. That's equivalent to the loop in the main program — it writes n records back-to-back — but is faster and shorter.

🐛 Common Pitfalls

  • Different struct definitions: The most common source of bugs. If you add or reorder fields between write and read, the file becomes unreadable.
  • Text mode: On Windows, "w"/"r" would translate line endings and corrupt the binary data. Always use "wb"/"rb".
  • Ignoring fwrite's return value: A short write (full disk, interrupted process) leaves the file incomplete. Always check.
  • Missing fclose: Buffered records won't reach disk until the buffer flushes, which may not happen if the program crashes.
  • Reading past the end of the file: The loop condition fread(...) == 1 handles this — a partial read returns 0 and the loop exits.
  • Storing a pointer in the struct: Pointers are process-specific. Their byte values on disk are meaningless in another run.
  • Endianness and padding: Files written on x86 won't read correctly on big-endian hardware, and struct padding may differ between compilers. For portable files, serialize each field individually with explicit types.

💡 Tips & Best Practices

  • Use sizeof(struct Student) rather than a hard-coded byte count — the struct layout can change between builds.
  • Write a magic number or version byte at the start of the file so future readers can detect format mismatches.
  • If your struct contains variable-length data (like strings), serialize each field individually with length prefixes rather than dumping the raw struct.
  • Store the record count as a header in the file if you need to know how many records exist before reading them all.
  • Compile with gcc -Wall -Wextra -std=c11 -g to catch type mismatches.
  • Run under valgrind to verify no memory leaks if you're dynamically allocating records.

📖 Related Tutorials in This Series

  • File Handling Assignments — Complete Index
  • 7. Write Data to a Binary File
  • 8. Read Binary Data from a Binary File and Display It
  • 3. Append Data to an Existing Binary File
  • 17. Random File Access with fseek, ftell, and rewind
  • Binary Files in C — Overview
  • Files FAQ

Previous Problem: -->> 15. Copy the Contents of One Text File into Another   ||   Next Problem: -->> 17. Demonstrate Random File Access with fseek, ftell, and rewind

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.