Writing entire structs to disk
What you'll learn: How to save a complete collection of related data to a file in one efficient step using fwrite.
The "Snapshot" Advantage
When we save data to a text file, we usually have to convert everything to strings. You might write a loop to print each member of a struct one by one, adding commas or newlines so you can read them back later.
Think of binary writing like taking a polaroid photo rather than drawing a map. Instead of describing every detail of your data, you are taking the exact pattern of 1s and 0s currently sitting in your computer's RAM and "freezing" them onto your hard drive. This is incredibly fast and keeps your data organized exactly as it exists in your program.
Using fwrite with Structs
To save a struct, we use the fwrite function. It doesn't care what is inside the struct; it only needs to know where the struct starts in memory and how many bytes it occupies. We use the & (address-of) operator to point to our variable and sizeof to calculate its footprint.
#include <stdio.h>
struct Player {
int id;
int health;
float stamina;
};
int main() {
struct Player hero = {1, 100, 75.5f};
// Open file in "wb" (write binary) mode
FILE *file = fopen("save.dat", "wb");
if (file != NULL) {
// 1. Pointer to data
// 2. Size of one item
// 3. Number of items
// 4. File pointer
fwrite(&hero, sizeof(struct Player), 1, file);
fclose(file);
}
return 0;
}
Why this matters
When you write a struct this way, the resulting file (save.dat) isn't meant to be read by humans in a text editor like Notepad—it will look like gibberish. However, for your program, it is perfect. Because the file is a bit-for-bit copy of the memory, you can later read that file directly back into a new struct variable with a single command.
This technique is the backbone of game save systems, database records, and image formats. It treats your data as a single "chunk" rather than a list of individual pieces.
Key takeaway
By passing the address and sizeof a struct to fwrite, you can save complex data structures to disk instantly without manual formatting.