file-handling · intermediate · ~15 min

Load a record

Deserialise a fixed record in the same field order.

Challenge

Deserialize the two-int record written by save_record, reading the fields back in the same order.

Task

Implement int load_record(const char *path, int *id, int *score) that reads two ints (native layout) from the file at path into *id and *score.

Input

  • path: filename of a file holding two ints (id then score), written by save_record.
  • id, score: pointers that receive the two values.

Output

Return 0 on success (with both values set), or -1 on failure (can't open or fewer than two ints available).

Example

file holds id=42, score=-7
load_record(path, &a, &b)   ->   0,  a = 42, b = -7
load_record("missing", &a, &b)   ->   -1

Edge cases

  • File can't be opened, or is too short: -1.

Rules

  • Read id then score in the same order they were written; both fread calls must return 1; open with "rb".

Input format

path: file to read. id/score: pointers for the two ints.

Output format

0 on success (both set), -1 on failure.

Constraints

Read id then score in write order; both reads must return 1.

Starter code

#include <stdio.h>

int load_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.