file-handling · intermediate · ~15 min

Save a record

Serialise a small fixed record to disk.

Challenge

Serialize a small fixed record (two ints) to a binary file, defining a simple on-disk format.

Task

Implement int save_record(const char *path, int id, int score) that writes id then score (two ints in native byte layout) to the file at path.

Input

  • path: filename to write (created/overwritten in the working directory).
  • id, score: the two values to store.

Output

Return 0 on success, or -1 on failure (can't open or short write).

Example

save_record("rec_fixture.bin", 7, 99)   ->   0
the file now holds the int 7 followed by the int 99

Edge cases

  • File can't be opened: -1.

Rules

  • Write id first, then score, each with fwrite(..., sizeof(int), 1, f); open with "wb"; close before returning.

Input format

path: file to write. id/score: ints to store.

Output format

0 on success, -1 on failure.

Constraints

Write id then score (native int layout) with "wb".

Starter code

#include <stdio.h>

int save_record(const char *path, int id, int score) {
    /* TODO */
    return -1;
}

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