AdvancedLesson 7 of 77 min read

Capstone: The Complete Data Logger With a Ring Buffer and a Binary Log

Bring the course together: a ring buffer that keeps the latest readings, a binary log file with a header written and read back, self-tests that run first, and a verification that reads the log file independently with Python.

In this lesson you will

  • Build a ring buffer
  • Write a binary file with a defined layout
  • Run self-tests first
  • Verify the file independently

About 28 minutes

Bruno’s logger, finished

The final project joins the course in one program: types and sizes, functions, pointers and dynamic memory, structs, file input and output, and tests. The logger keeps the most recent readings in a ring buffer, a fixed-size array that wraps around, so that memory use never grows however long the logger runs. When it is switched off, it writes the buffer to a binary file with a small header. A second program, or in this lesson a different language, can read that file back, which makes the file format the contract between them.

A ring buffer has a capacity, a count and a position for the next write. Writing stores at that position and moves it on, wrapping to zero at the end, and when the buffer is full the oldest reading is overwritten. Reading the readings in order starts from the oldest one. The file format is defined byte by byte, and not by writing whole structs, because padding and byte order would make a struct dump depend on the compiler. The header holds four bytes of magic text, “BLOG”, a 32-bit version, a 32-bit count, and then the values as 64-bit floating point numbers, all in little-endian order, which the program writes explicitly with a small helper, so the file is the same on any machine.

Offset Size Content
0 4 bytes Magic text BLOG
4 4 bytes Version, little-endian
8 4 bytes Count of readings, little-endian
12 8 x count The readings, oldest first, as IEEE 754 doubles in little-endian order
#define _DEFAULT_SOURCE
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct { double buf[5]; size_t count, next; } Ring;

static void ring_add(Ring *r, double v) {
    r->buf[r->next] = v;
    r->next = (r->next + 1) % 5;
    if (r->count < 5) r->count++;
}
static double ring_at(const Ring *r, size_t i) {      /* i = 0 is the oldest */
    size_t start = r->count < 5 ? 0 : r->next;
    return r->buf[(start + i) % 5];
}
static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
static uint32_t get32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; }
static int save(const Ring *r, const char *path) {
    FILE *f = fopen(path, "wb");
    if (!f) return -1;
    uint8_t head[12];
    memcpy(head, "BLOG", 4); put32(head + 4, 1); put32(head + 8, (uint32_t)r->count);
    fwrite(head, 1, 12, f);
    for (size_t i = 0; i < r->count; i++) {
        double v = ring_at(r, i);
        uint64_t bits; memcpy(&bits, &v, 8);
        uint8_t b[8]; for (int k = 0; k < 8; k++) b[k] = (uint8_t)(bits >> (8 * k));
        fwrite(b, 1, 8, f);
    }
    return fclose(f);
}
static int load(Ring *r, const char *path) {
    FILE *f = fopen(path, "rb");
    if (!f) return -1;
    uint8_t head[12];
    if (fread(head, 1, 12, f) != 12 || memcmp(head, "BLOG", 4) != 0 || get32(head + 4) != 1) { fclose(f); return -2; }
    uint32_t n = get32(head + 8);
    memset(r, 0, sizeof *r);
    for (uint32_t i = 0; i < n; i++) {
        uint8_t b[8];
        if (fread(b, 1, 8, f) != 8) { fclose(f); return -3; }
        uint64_t bits = 0; for (int k = 0; k < 8; k++) bits |= (uint64_t)b[k] << (8 * k);
        double v; memcpy(&v, &bits, 8);
        ring_add(r, v);
    }
    fclose(f);
    return 0;
}

int main(void) {
    Ring t = {{0}, 0, 0};
    for (int i = 1; i <= 3; i++) ring_add(&t, i);
    assert(t.count == 3 && ring_at(&t, 0) == 1 && ring_at(&t, 2) == 3);
    for (int i = 4; i <= 7; i++) ring_add(&t, i);
    assert(t.count == 5 && ring_at(&t, 0) == 3 && ring_at(&t, 4) == 7);
    assert(load(&t, "/tmp/does/not/exist.blog") == -1);
    printf("all self-tests passed\n");

    Ring r = {{0}, 0, 0};
    double readings[] = {20.5, 21.0, 21.5, 22.0, 22.5, 23.0, 23.5, 24.0};
    for (int i = 0; i < 8; i++) ring_add(&r, readings[i]);
    printf("added 8 readings to a ring of 5; kept:");
    for (size_t i = 0; i < r.count; i++) printf(" %.1f", ring_at(&r, i));
    printf("\n");
    const char *tpl = "/tmp/c_logger_capstone.blog";
    assert(save(&r, tpl) == 0);
    FILE *f = fopen(tpl, "rb"); fseek(f, 0, SEEK_END); long size = ftell(f); fclose(f);
    printf("saved to %s, size %ld bytes\n", "the log file", size);
    Ring back = {{0}, 0, 0};
    int rc = load(&back, tpl);
    int same = rc == 0 && back.count == r.count;
    for (size_t i = 0; same && i < r.count; i++) same = ring_at(&back, i) == ring_at(&r, i);
    printf("loaded back: rc %d, identical: %d\n", rc, same);
    return 0;
}
all self-tests passed
added 8 readings to a ring of 5; kept: 22.0 22.5 23.0 23.5 24.0
saved to the log file, size 52 bytes
loaded back: rc 0, identical: 1

The self-tests ran first and passed: the ring buffer keeps all readings until it is full, and then overwrites the oldest one, and a missing file is reported with a negative code. Then eight readings went into a ring of five, and only the latest five survived, oldest first: 22.0 22.5 23.0 23.5 24.0. The program saved them to a temporary file of 52 bytes, which is the 12-byte header plus 5 x 8 bytes of values, loaded the file back, and found the readings identical (return code 0, identical 1). It ran under AddressSanitizer and UndefinedBehaviorSanitizer without a report.

The decisive check is a different program reading the file. The course opened the log in Python and decoded it with the struct module using the documented layout: the magic text is BLOG, the version 1, the count 5, and the five readings are [22.0, 22.5, 23.0, 23.5, 24.0]. They equal what the C program printed, so the file format is really what the table says, and not merely something that the same C code can read back. That is exactly the kind of test that catches mistakes in byte order or in offsets, which a round trip through the same code cannot.

Check by hand: the eight readings are 20.5 to 24.0 in steps of 0.5. The ring has five slots, so the three oldest, 20.5, 21.0 and 21.5, were overwritten, and the five newest remain: 22.0, 22.5, 23.0, 23.5, 24.0. The file size is 12 + 5 x 8 = 52 bytes.

Never dump structs into a file format

Padding, alignment and byte order depend on the compiler and machine. Define the format byte by byte, as the header table does, and write and read each field explicitly.

Test formats with a second program

A reader written independently, here in Python, finds format mistakes that a round trip through the same code hides. Keep a small sample file in your tests.

About this course

Every program in this lesson was compiled with GCC 13 using -std=c17 -Wall -Wextra and run while the course was written. Compilers and platforms differ, so check your compiler’s documentation, and the C standard drafts, for details that the standard leaves open. mkstemp is POSIX. The file lives in a temporary folder and is removed after the check.

Where to go next

  • Read the log file from a real sensor, such as a serial port or an I2C device, with the platform’s library, using the habits from this course.
  • Add a checksum, such as CRC-32, to the file format and verify it when loading.
  • Study the C standard library in more depth: time.h, signal.h, and the POSIX file and process functions.
  • Learn a build and test setup for your platform: CMake, Meson or plain make, with sanitizers and clang-tidy on every change.
  • Read well-known C code, such as the Linux kernel, SQLite and the Lua interpreter, to see how experts structure larger programs.

Practice

Add a checksum to the header and make load reject a file with a wrong checksum. Flip one byte of the saved file and check that the loader reports the error. Extend the Python reader to compute the mean of the readings and compare it with the C program.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a ring buffer do when it is full?

  1. Stops
  2. Allocates more memory
  3. Crashes
  4. Overwrites the oldest reading

Memory use stays constant.

Why define the file format byte by byte?

  1. It is faster
  2. C forbids structs
  3. Structs depend on padding and byte order
  4. Files cannot hold structs

The format is a contract.

What did the independent reader confirm?

  1. The program is fast
  2. Nothing
  3. The file matches the documented layout
  4. The disk is healthy

The magic, version, count and values matched.

Why do the self-tests run first?

  1. To waste time
  2. To stop on broken logic before doing real work
  3. To print more
  4. To use memory

A safety habit.

How big is the file for 5 readings?

  1. 40 bytes
  2. 52 bytes
  3. 20 bytes
  4. 100 bytes

12 header bytes plus 5 x 8.

Summary

  • A ring buffer keeps the latest readings in constant memory.
  • A file format is a byte-level contract; write each field explicitly.
  • Self-tests run first, and sanitizers watch the run.
  • An independent reader in another language verifies the format.

Next lesson

This completes the C course. Keep building small projects with warnings, sanitizers and tests turned on, and read other people’s C code.

Questions

Is little-endian a good choice?

It matches most modern processors, so reading and writing need no conversion in practice. What matters is that the format states its choice, so that every reader agrees.

What if the file is corrupt?

The loader checks the magic, the version and the length, and returns an error code. A checksum would also detect damaged values.

What should I learn after this course?

Pick a domain, such as embedded systems, operating systems or tools, and read the code of a project in it. C++ and Rust are natural next languages.

Progress is saved in this browser.