Binary Data Engineering

Binary Data Engineering in C: A text file describes your data: the number 250 becomes the three characters , , , and something has to read them back and…

The Analogy: A Photocopy, Not a Description

A text file describes your data: the number 250 becomes the three characters 2, 5, 0, and something has to read them back and rebuild the integer. A binary file is a photocopy of the bytes — the four bytes that made up the int in memory are the four bytes on disk, and reading them back is a straight copy in the other direction. No parsing, no formatting, no rounding.

That gives binary files two abilities text files cannot match. Every record is the same size, so record number 500 lives at offset 500 * sizeof(record) and you can jump to it without reading the first 499. And a double survives the round trip exactly, instead of being printed with six decimal places and read back slightly different.

The catch is the flip side of the same coin: a photocopy is only meaningful to a machine that lays out data the same way. Padding, byte order and type sizes are all baked into the copy. That makes binary perfect for a program's own working files and a poor choice for anything another program — or another architecture — has to read.


Syntax or Core Structure

#include <stdio.h>

struct Record { int id; char name[16]; double price; };

int main(void) {
    struct Record out[3] = {
        { 101, "bolt",   0.35 },
        { 102, "nut",    0.20 },
        { 103, "washer", 0.10 },
    };

    FILE *f = fopen("items.dat", "wb");            /* note the b */
    if (f == NULL) { perror("items.dat"); return 1; }

    size_t n = fwrite(out, sizeof out[0], 3, f);   /* returns ITEMS written */
    if (n != 3) { fprintf(stderr, "short write: %zu\n", n); fclose(f); return 1; }
    if (fclose(f) != 0) { perror("closing items.dat"); return 1; }

    f = fopen("items.dat", "rb");
    if (f == NULL) { perror("items.dat"); return 1; }

    /* Jump straight to record 1 without reading record 0. */
    long offset = 1L * (long)sizeof(struct Record);
    if (fseek(f, offset, SEEK_SET) != 0) { perror("fseek"); fclose(f); return 1; }

    struct Record one;
    if (fread(&one, sizeof one, 1, f) != 1) {
        fprintf(stderr, "short read\n"); fclose(f); return 1;
    }
    printf("record 1: %d %s %.2f\n", one.id, one.name, one.price);
    printf("offset now %ld\n", ftell(f));

    fseek(f, 0, SEEK_END);
    long bytes = ftell(f);
    printf("file %ld bytes = %ld records of %zu\n",
           bytes, bytes / (long)sizeof(struct Record), sizeof(struct Record));

    fclose(f);
    return 0;
}

Output:

record 1: 102 nut 0.20
offset now 64
file 96 bytes = 3 records of 32

Work through the arithmetic, because every later technique rests on it. struct Record is 32 bytes on a typical 64-bit compiler: 4 for the int, 16 for the array, then the double must start at a multiple of 8 so four padding bytes are inserted, putting it at offset 24 and ending the struct at 32. Record 1 therefore begins at byte 32; after reading 32 bytes the bookmark sits at 64; three records make 96 bytes.

Those four padding bytes are written to the file along with everything else. They are not initialised to anything in particular, which is the first hint that a struct dump is not a portable format.


Technical Depth: Sizes, Seeks, and Why Layout Leaks

Text fileBinary file
A double round triplimited by the format you printed withexact, byte for byte
Record sizevaries with the datafixed, so record i is at i * sizeof
Human-readableyesno
Portable between machinesyesonly with deliberate encoding
Newline translationhappens in text modesuppressed by b
Typical uselogs, config, interchangecaches, indexes, save files

fread and fwrite count items, not bytes

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

Both return the number of complete items transferred, so the test is != nmemb, never < 0. A partial final item is a truncated file, which is exactly the corruption you want to detect. Passing size and nmemb the other way round still moves the same number of bytes but makes the return value useless for detecting a partial record.

Positioning

CallEffect
fseek(f, off, SEEK_SET)off bytes from the start
fseek(f, off, SEEK_CUR)off bytes from the current position, negative to go back
fseek(f, 0, SEEK_END)the end, so ftell then gives the size in bytes
ftell(f)current byte offset, or -1L on failure
rewind(f)back to the start, and clears the error and EOF flags

ftell and fseek use long, which on some platforms caps you at 2 GB; larger files need the platform's fseeko/ftello or equivalent. And note fseek clears the end-of-file flag, which is why seeking is the way to reuse a stream that has already hit EOF.

Read-then-write on the same stream needs a seek between

With an update mode such as "r+b", you must call fseek, fflush or rewind when switching from reading to writing, and a seek when switching back. Skipping it is undefined behaviour, and in practice produces writes at a surprising offset. Since a random-access update wants the seek anyway, the rule costs nothing to follow.

What makes a struct dump non-portable

Four things, any one of which is enough to break a file written elsewhere:

  • Padding. The four unused bytes in struct Record are compiler-chosen; a different compiler may pick a different layout.
  • Byte order. 0x0000006D is stored little-endian on x86 and ARM as 6D 00 00 00, big-endian elsewhere as 00 00 00 6D.
  • Type sizes. int is 4 bytes almost everywhere but long is 8 on Linux and 4 on Windows.
  • Floating-point representation. Nearly always IEEE-754 today, but the standard does not require it.

So when a file must outlive the program that wrote it, serialise field by field with fixed-width types from <stdint.h> and a chosen byte order:

#include <stdint.h>

static void put_u32_be(unsigned char *p, uint32_t v) {
    p[0] = (unsigned char)(v >> 24);
    p[1] = (unsigned char)(v >> 16);
    p[2] = (unsigned char)(v >> 8);
    p[3] = (unsigned char)v;
}

static uint32_t get_u32_be(const unsigned char *p) {
    return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16)
         | ((uint32_t)p[2] << 8)  |  (uint32_t)p[3];
}

This works identically on every machine because it never asks what order the bytes are in — it puts them there itself. Pair it with a small header holding a magic number and a format version, so a program reading an old file can say "version 1, I need version 2" instead of misreading it.

Never write a pointer to a file

struct Bad { char *name; };      /* the address, not the text */

An address is meaningful only inside the process that produced it. Writing one stores a number that will point at nothing on the next run — and reading it back gives you a pointer that looks valid and crashes on use. Fixed-size arrays, or a length followed by the characters, are the two ways to store variable text.

The b is not optional

On Windows, text mode converts \n to a two-byte line ending on the way out and back on the way in. Applied to binary data, every byte that happens to equal 0x0A gains a companion, and the file silently grows and misaligns. On Linux and macOS "rb" and "r" behave identically, so the habit costs nothing and saves you the day the code is built on Windows.


Real World Example: Updating One Record In Place

This is what fixed-size records are for. Adjusting a quantity rewrites 32 bytes at a known offset — the rest of the file is never touched, no matter how large it grows.

#include <stdio.h>

struct Item { int id; char name[16]; int quantity; double price; };

/* Record index of the item with this id, or -1. */
static long find_index(FILE *f, int id) {
    rewind(f);
    struct Item it;
    long index = 0;
    while (fread(&it, sizeof it, 1, f) == 1) {
        if (it.id == id) return index;
        index++;
    }
    return -1;
}

/* New quantity on success, -1 if missing or the change would go negative. */
static int update_quantity(FILE *f, int id, int delta) {
    long index = find_index(f, id);
    if (index < 0) return -1;

    long offset = index * (long)sizeof(struct Item);
    if (fseek(f, offset, SEEK_SET) != 0) return -1;

    struct Item it;
    if (fread(&it, sizeof it, 1, f) != 1) return -1;
    if (it.quantity + delta < 0) return -1;
    it.quantity += delta;

    if (fseek(f, offset, SEEK_SET) != 0) return -1;   /* mandatory read -> write seek */
    if (fwrite(&it, sizeof it, 1, f) != 1) return -1;
    if (fflush(f) != 0) return -1;
    return it.quantity;
}

find_index scans, which is the honest limitation of this design; a real store keeps an index so lookups do not read the whole file. The update is what matters here — it is a seek and a 32-byte write, independent of file size.

int main(void) {
    const struct Item seed[] = {
        { 101, "bolt",    250, 0.35 },
        { 102, "nut",     480, 0.20 },
        { 103, "washer",  120, 0.10 },
        { 104, "bracket",  30, 4.75 },
    };
    const size_t count = sizeof seed / sizeof seed[0];

    FILE *f = fopen("items.dat", "wb");
    if (f == NULL) { perror("items.dat"); return 1; }
    if (fwrite(seed, sizeof seed[0], count, f) != count) {
        fprintf(stderr, "short write\n"); fclose(f); return 1;
    }
    if (fclose(f) != 0) { perror("closing items.dat"); return 1; }

    f = fopen("items.dat", "r+b");                 /* read and write, no truncation */
    if (f == NULL) { perror("items.dat"); return 1; }

    fseek(f, 0, SEEK_END);
    printf("items.dat: %ld bytes, %zu records of %zu\n\n",
           ftell(f), count, sizeof(struct Item));

    int q = update_quantity(f, 103, 40);
    printf("washer +40 -> %s", q < 0 ? "refused\n" : "");
    if (q >= 0) printf("quantity %d\n", q);

    q = update_quantity(f, 101, -300);
    printf("bolt -300 -> %s\n", q < 0 ? "refused" : "updated");

    rewind(f);
    struct Item it;
    while (fread(&it, sizeof it, 1, f) == 1)
        printf("%3d  %-10s %5d %8.2f\n", it.id, it.name, it.quantity, it.price);

    if (ferror(f)) { perror("reading items.dat"); fclose(f); return 1; }
    if (fclose(f) != 0) { perror("closing items.dat"); return 1; }
    return 0;
}

Output:

items.dat: 128 bytes, 4 records of 32

washer +40 -> quantity 160
bolt -300 -> refused
101  bolt         250     0.35
102  nut          480     0.20
103  washer       160     0.10
104  bracket       30     4.75

128 bytes is 4 records of 32 — the same layout arithmetic as before, now with quantity filling what had been padding, so the struct size did not change. The washer's 120 became 160 and nothing else moved; the bolt's update was refused before any write, because 250 - 300 is negative, so the file still says 250.

Three properties are worth naming:

  1. The refusal happens between the read and the write. Validating after fwrite would mean repairing a file you had already damaged.
  2. "r+b" opens without truncating. "wb" would have emptied the file the moment it opened, which is why the seed data is written in a separate, deliberate step.
  3. The fflush makes the change durable before the next operation. Without it the update sits in a buffer, and a crash mid-run loses a change the program has already reported as done.

Common Mistakes

  1. Omitting the b. On Windows, text mode rewrites every byte equal to 0x0A, so the file grows and every offset after the first newline-like byte is wrong. Always "rb", "wb", "r+b".
  2. Comparing fread's return value to -1 or 0 only. It returns items transferred; the test is != n. A short count means a truncated file, and treating it as success reads half a record as a whole one.
  3. Writing to a file opened with "wb" when you meant to update. "wb" truncates on open. Update in place with "r+b".
  4. Switching between reading and writing without a seek. On an update-mode stream, a fwrite straight after a fread is undefined; put an fseek (or fflush) between them.
  5. Writing a struct containing a pointer. The address is stored, and it means nothing on the next run. Store a fixed-size array, or a length plus the bytes.
  6. Assuming a struct dump is portable. Padding, byte order, long size and float format all differ between platforms. Encode field by field with <stdint.h> types for anything shared.
  7. Computing record offsets with a hardcoded number. fseek(f, index * 32, SEEK_SET) breaks the day a member is added. Always index * (long)sizeof(struct Item).
  8. Forgetting that a partial write leaves the file corrupt. fwrite can stop mid-way on a full disk. Check the count, and for critical data write to a temporary file and rename it only after a successful fclose.

Best Practices

  • Use binary for files only your program reads: caches, indexes, save states. Use text for logs, configuration and anything a human or another tool touches.
  • Give every binary format a header with a magic number and a version integer, and refuse to read a version you do not understand.
  • Derive every offset from sizeof, never from a literal byte count.
  • Check the item count from every fread and fwrite, then ferror after the loop, then fclose.
  • Keep records fixed-size when you want random access; that property is the entire reason to choose binary.
  • Serialise with fixed-width types and an explicit byte order whenever the file may cross machines or compiler versions.
  • fflush after an update you have already reported as complete, and write-then-rename when a half-written file would be worse than none.
  • Inspect binary output with a hex viewer while developing — xxd items.dat or od -t x1 — so padding and byte order are visible rather than assumed.

Practice Exercises

  1. See the padding and the byte order. Write the three-record example, then run xxd items.dat (or od -A d -t x1 items.dat) and annotate the first 32 bytes: which are the id, which are the name, which are padding, which are the double. Write down whether your machine stored 101 as 65 00 00 00 or 00 00 00 65, and say which endianness that is. Then add int quantity; after name, rerun, and explain why sizeof did not change.
  2. A portable format. Rewrite the same three records using put_u32_be/get_u32_be for the id, a fixed 16-byte name field, and the price as a uint32_t count of hundredths of a currency unit instead of a double. Prefix the file with the four bytes ITM1 and a version. Confirm the file is exactly the size you predicted, verify the round trip, and then make the reader reject a file whose magic or version is wrong.
  3. Append, then random-access read. Build a program with two modes: add <id> <name> <qty> <price> opens with "ab" and appends one record, while get <index> opens with "rb", seeks to index * sizeof(struct Item) and prints that record. Add four items in separate runs, read them back out of order, and make get detect an index past the end by comparing against the file size from fseek/ftell rather than by letting fread fail.