c / intermediate
Snippet
Binary I/O with Structs
Binary file operations use 'fwrite' and 'fread' to transfer raw memory blocks to disk. This is faster and more compact than text conversion but requires the same memory layout when reading back.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>struct Config { int id; float value; };void save_config(struct Config *c) {FILE *f = fopen("config.bin", "wb");if (f) {fwrite(c, sizeof(struct Config), 1, f);fclose(f);}}
Breakdown
1
fwrite(c, sizeof(struct Config), 1, f);
Writes the exact memory content of the struct to the file stream.
2
"wb"
Mode string for 'write binary', essential for non-text data on many systems.