Back to Blog

C in 100 Seconds: Binary File I/O

Daryl WongDaryl Wong

Video: C in 100 Seconds: Binary File I/O — fread and fwrite | Episode 37 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Binary File I/O

Binary file I/O writes raw memory to disk and reads it back. No formatting, no parsing — just bytes. It is faster and more compact than text I/O.

fwrite — Save Data to Disk

Student students[3] = {
  {"Alice", 20, 95.5},
  {"Bob", 22, 87.3},
  {"Carol", 21, 91.0},
};

FILE *f = fopen("/tmp/students.dat", "wb");
fwrite(students, sizeof(Student), 3, f);
fclose(f);

fwrite takes four arguments: the data pointer, the size of one element, the count, and the file. Open with "wb" for write binary.

fread — Load Data Back

Student loaded[3];
FILE *f2 = fopen("/tmp/students.dat", "rb");
int count = fread(loaded, sizeof(Student), 3, f2);
fclose(f2);

fread mirrors fwrite — same four arguments. It returns how many items were actually read, which may be less if the file is shorter than expected.

Works with Any Type

int nums[] = {10, 20, 30, 40, 50};
FILE *f3 = fopen("/tmp/nums.dat", "wb");
fwrite(nums, sizeof(int), 5, f3);
fclose(f3);

Structs, integers, floats, arrays — binary I/O handles them all. The data comes back exactly as it went in, no conversion needed.

Student Code

Try it yourself: episode37/binary.c