typestar

Binary reads and writes in C

fread and fwrite move records, and both return how many they handled.

#include <stdio.h>

typedef struct {
    int id;
    double score;
} Record;

size_t save_records(const char *path, const Record *rows, size_t n) {
    FILE *f = fopen(path, "wb");
    if (f == NULL) {
        return 0;
    }
    size_t written = fwrite(rows, sizeof(Record), n, f);
    fclose(f);
    return written;
}

size_t load_records(const char *path, Record *rows, size_t max) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return 0;
    }
    size_t read = fread(rows, sizeof(Record), max, f);
    fclose(f);
    return read;
}

How it works

  1. The element size and count are separate arguments.
  2. A short return value means end of file or an error.
  3. Struct layout differs between machines, so this is not a portable format.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
481
Tokens
150
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 2 of 4 in Writing & binary, step 6 of 12 in Files & I/O.

← Previous Next →