Saving the data store to a binary file
What you'll learn: How to write an entire array of structures from memory directly into a permanent file using binary mode.
So far, your data store lives only in RAM. If you turn off your computer, your data vanishes. To make it permanent, we need to save it to a file. While we could use text (like a .txt file), saving in binary mode is faster and more efficient because it writes the data exactly as it looks in your computer's memory.
Thinking in Blocks
Imagine your data store is a long shelf of identical boxes (an array of structs). Saving to a text file is like opening every box, reading the contents, and writing a description on a piece of paper. Saving to a binary file is like taking a giant photo of the entire shelf. We don't care what is inside the boxes; we just copy the raw bits and bytes.
To do this, we use fwrite(). This function needs four things:
- A pointer to the start of your data.
- The size of one single "box" (
sizeofyour struct). - How many boxes you are saving.
- The file you want to put them in.
Implementing the Save
When opening the file with fopen(), we must use the "wb" mode, which stands for "write binary." This tells the operating system not to mess with line endings or formatting.
#include <stdio.h>
typedef struct {
int id;
float price;
} Item;
void save_data(const char *filename, Item *inventory, int count) {
// Open for Writing in Binary mode
FILE *file = fopen(filename, "wb");
if (file == NULL) {
printf("Error: Could not open file for writing.\n");
return;
}
// Write all items in one go
size_t written = fwrite(inventory, sizeof(Item), count, file);
if (written == count) {
printf("Successfully saved %d items.\n", count);
} else {
printf("Error: Only saved %zu items.\n", written);
}
fclose(file);
}
Why Binary?
Because binary files are just raw memory dumps, they are incredibly fast. You don't have to convert numbers to strings or add commas. However, keep in mind that these files aren't "human-readable." If you open the resulting file in Notepad, it will look like gibberish. That’s okay! Your C program knows exactly how to read that gibberish back into the array later.
Key takeaway
Use fwrite() with the "wb" mode to copy raw structs from memory to a file, providing a fast and efficient way to persist your data store.