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
#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
4 8 15 16 23 42Common 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.
Recommended next exercise
- Files in C: solved exercise to count lines and characters
- Strings in C: solved exercises with strlen, strcpy, and strcmp
- Binary tree in C: solved insertion and search exercise
- All C exercises
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.