Lesson 3 of 8
Binary Persistence - store.c
The store module reads and writes the entire `TaskList` to a binary file. The format: a 4-byte magic number, a 4-byte version, a 4-byte count, and then `count` fixed-size `Task` records. This layout allows forward-compatibility checks and O(1) record access by index via `fseek`.
store.h & store.c - Binary File I/O
/* store.h */
#ifndef STORE_H
#define STORE_H
#include "task.h"
#define STORE_MAGIC 0x5441534Bu /* "TASK" in little-endian */
#define STORE_VERSION 1U
#define DEFAULT_DB "tasks.bin"
int store_load(const char *path, TaskList *tl);
int store_save(const char *path, const TaskList *tl);
#endif
/* store.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "store.h"
typedef struct {
uint32_t magic;
uint32_t version;
uint32_t count;
uint8_t _pad[4];
} FileHeader;
int store_load(const char *path, TaskList *tl) {
FILE *fp = NULL;
int rc = -1;
fp = fopen(path, "rb");
if (!fp) {
if (errno == ENOENT) return 0; /* first run: empty database */
perror("store_load: fopen"); goto cleanup;
}
FileHeader hdr;
if (fread(&hdr, sizeof(hdr), 1, fp) != 1) {
perror("store_load: fread header"); goto cleanup;
}
if (hdr.magic != STORE_MAGIC) {
fprintf(stderr, "store_load: bad magic in %s
", path); goto cleanup;
}
if (hdr.version != STORE_VERSION) {
fprintf(stderr, "store_load: unsupported version %u
", hdr.version);
goto cleanup;
}
for (uint32_t i = 0; i < hdr.count; i++) {
Task t;
if (fread(&t, sizeof(Task), 1, fp) != 1) {
perror("store_load: fread task"); goto cleanup;
}
if (t.status != STATUS_DELETED) /* skip soft-deleted on load */
if (tasklist_push(tl, &t) != 0) goto cleanup;
}
rc = 0;
cleanup:
if (fp) fclose(fp);
return rc;
}
int store_save(const char *path, const TaskList *tl) {
FILE *fp = NULL;
int rc = -1;
fp = fopen(path, "wb");
if (!fp) { perror("store_save: fopen"); return -1; }
/* Count non-deleted tasks */
uint32_t count = 0;
for (size_t i = 0; i < tl->size; i++)
if (tl->data[i].status != STATUS_DELETED) count++;
FileHeader hdr = { STORE_MAGIC, STORE_VERSION, count, {0} };
if (fwrite(&hdr, sizeof(hdr), 1, fp) != 1) {
perror("store_save: fwrite header"); goto cleanup;
}
for (size_t i = 0; i < tl->size; i++) {
if (tl->data[i].status == STATUS_DELETED) continue;
if (fwrite(&tl->data[i], sizeof(Task), 1, fp) != 1) {
perror("store_save: fwrite task"); goto cleanup;
}
}
rc = 0;
cleanup:
if (fp) fclose(fp);
return rc;
}Common Mistakes
- Writing struct with internal pointers to a binary file - if `Task` had a `char *title` pointer instead of `char title[64]`, writing `sizeof(Task)` would write the pointer address, not the string. Always use fixed-size char arrays in binary-serialised structs.
- Not writing a magic number - without a magic header, your tool will happily 'load' any random binary file and produce garbage. The magic check provides a fast sanity check.
- Not handling `ENOENT` for first run - if the database file doesn't exist yet and you just `perror`, the tool fails on first use. Check `errno == ENOENT` after `fopen` fails on `"rb"` and treat it as an empty database.
Tip
Tip
Practice Binary Persistence storec in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Binary disk storage serializes key-value records with length prefixes and integrity checksums
Practice Task
Note
Practice Task - (1) Write a working example of Binary Persistence storec from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Binary Persistence storec is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.
Key Takeaways
- The store module reads and writes the entire `TaskList` to a binary file.
- Writing struct with internal pointers to a binary file - if `Task` had a `char *title` pointer instead of `char title[64]`, writing `sizeof(Task)` would write the pointer address, not the string. Always use fixed-size char arrays in binary-serialised structs.
- Not writing a magic number - without a magic header, your tool will happily 'load' any random binary file and produce garbage. The magic check provides a fast sanity check.
- Not handling `ENOENT` for first run - if the database file doesn't exist yet and you just `perror`, the tool fails on first use. Check `errno == ENOENT` after `fopen` fails on `"rb"` and treat it as an empty database.
Finished this lesson?