Reading structs back into memory
What you'll learn: How to use fread() to instantly reconstruct complex data structures from a binary file back into your program's variables.
The "Instant Replay" of Data
Imagine you are playing a board game and need to pause. You could write down every piece's position on a piece of paper (Text I/O), or you could simply take a photo of the board. When you return, you look at the photo and put everything back exactly where it was.
In C, reading a struct from a binary file is like that photo. Instead of reading a single integer or a single character, you are telling the computer: "Go to this file, grab a chunk of bytes the exact size of my struct, and drop them directly into this variable."
Using fread() for Structs
To get data back, we use the fread() function. It works identically to fwrite(), but in reverse. It needs to know four things: where to store the data (the address of your struct), how big one struct is, how many you want to read, and which file to look in.
Here is how you bring a "Player" profile back to life:
#include <stdio.h>
struct Player {
int level;
float health;
char rank;
};
int main() {
FILE *file = fopen("savegame.bin", "rb"); // 'rb' means Read Binary
struct Player hero;
if (file != NULL) {
// Read 1 struct-sized chunk of data into the &hero address
fread(&hero, sizeof(struct Player), 1, file);
printf("Hero loaded! Level: %d, Health: %.1f\n", hero.level, hero.health);
fclose(file);
}
return 0;
}
Why this is powerful
Notice that we didn't have to parse the text or convert strings back into numbers. Because binary files store data in the exact same format the CPU uses, fread() simply copies the raw bits from the disk into your RAM. The hero variable is instantly populated with its original level, health, and rank as if it never left.
However, remember the "Golden Rule" of binary files: you must read the data back using the exact same struct definition used to write it. If the structure changes by even one byte, the data will "shift," and your program will read the wrong values into the wrong fields.
Key takeaway
Use fread() with the sizeof operator to pull entire blocks of structured data from a file directly into a variable in one quick step.