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.
📝 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.
- Define the struct — a
Studentwithid,name, andmarks. - Fill an array of
Studentrecords (or read them from user input). - Open the file in binary write mode (
"wb"). - Write each record with
fwrite(&students[i], sizeof(struct Student), 1, fp). - Close the file so all records reach disk.
- Reopen the file in binary read mode (
"rb"). - Read each record with
fread(&s, sizeof(struct Student), 1, fp)until it returns 0. - 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
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. |
🔁 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(...) == 1handles 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 -gto catch type mismatches. - Run under
valgrindto verify no memory leaks if you're dynamically allocating records.