file-handling · intermediate · ~15 min

Read one binary int

fread a fixed-size record.

Challenge

Read one binary int back from a file — the raw bytes of an int written earlier.

Task

Implement int read_int_binary(const char *path, int *out) that reads a single int (native byte layout) from the start of the file at path into *out.

Input

  • path: filename of a file holding at least sizeof(int) bytes (the grader writes it).
  • out: pointer that receives the value.

Output

Return 0 on success (with *out set), or -1 on any failure (can't open, or fewer than sizeof(int) bytes available).

Example

file holds the int 12345
read_int_binary(path, &got)   ->   0,  got = 12345
read_int_binary("missing", &got)   ->   -1

Edge cases

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

Rules

  • fread(out, sizeof(int), 1, f) must return 1; open in binary mode; close before returning.

Input format

path: file to read. out: pointer for the int value.

Output format

0 on success (*out set), or -1 on any failure.

Constraints

fread one int (native layout); binary mode; the read must return 1.

Starter code

#include <stdio.h>

int read_int_binary(const char *path, int *out) {
    /* TODO */
    return -1;
}

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