file-handling · intermediate · ~15 min

Write one binary int

fwrite a single fixed-size value.

Challenge

Write a single int to a file as raw bytes, so it can be read back later.

Task

Implement int write_int_binary(const char *path, int v) that writes the int v (native byte layout) to the file at path.

Input

  • path: filename to write (created/overwritten in the working directory).
  • v: the value to store.

Output

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

Example

write_int_binary("wi_fixture.bin", 4242)   ->   0
later: reading one int back from the file yields 4242

Edge cases

  • File can't be opened: -1.

Rules

  • fwrite(&v, sizeof v, 1, f) must return 1; open with "wb"; close before returning.

Input format

path: file to write. v: int value to store.

Output format

0 on success, -1 on failure.

Constraints

fwrite one int (native layout) with "wb"; the write must return 1.

Starter code

#include <stdio.h>

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

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