file-handling · intermediate · ~12 min

Read a fixed-size record

Bounds-checked indexing into a fixed-record buffer.

Challenge

Your job

#include <stdint.h>
#include <stddef.h>
int read_record(const uint8_t *buf, size_t n, size_t recsize, int idx, unsigned char *out);

Copy the idx-th recsize-byte record from buf into out. Return 0 on success, or -1 on NULL, recsize == 0, negative idx, or a record that runs past n.

Hints

  1. The record starts at idx * recsize.
  2. Verify start + recsize <= n before copying.

Why this matters

Binary formats (databases, MFT, packet logs) are arrays of fixed-size records; reading record N is just bounds-checked indexing.

Starter code

#include <stdint.h>
#include <stddef.h>
int read_record(const uint8_t *buf, size_t n, size_t recsize, int idx, unsigned char *out) {
    /* TODO */
    (void)buf; (void)n; (void)recsize; (void)idx; (void)out;
    return -1;
}

Common mistakes

Integer overflow on idx×recsize (guard with the bound check). Off-by-one letting the last record read past n.

Edge cases to handle

Last valid record. idx one past the end. recsize 0.

Complexity

O(recsize).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.