fread and fwrite in C: solved binary file exercise

fread and fwrite in C: solved exercise

If you searched for fread and fwrite in C solved exercise, this page shows the full binary write/read workflow.

Problem statement

Write an integer array to a binary file and read it back into another array.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>

int main(void) {
    int data[] = {4, 8, 15, 16, 23, 42};
    int copy[6] = {0};

    FILE *f = fopen("data.bin", "wb");
    if (!f) return 1;
    fwrite(data, sizeof(int), 6, f);
    fclose(f);

    f = fopen("data.bin", "rb");
    if (!f) return 1;
    fread(copy, sizeof(int), 6, f);
    fclose(f);

    for (int i = 0; i < 6; i++) printf("%d ", copy[i]);
    printf("\n");
    return 0;
}

Expected output

1
4 8 15 16 23 42

Common mistakes

  • Opening in text mode (w/r) instead of binary (wb/rb).
  • Not checking actual items read/written.
  • Ignoring type-size portability across systems.

Practical use

Binary formats are common for compact datasets, telemetry streams, and state snapshots.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.