file-handling · beginner · ~10 min

Read a file into a bounded buffer

Open, bounded-read, and close a file safely.

Challenge

Open a file, read up to a fixed number of bytes into a buffer, and report how many you got — the first half of nearly every file tool.

Task

Implement long read_file_bytes(const char *path, unsigned char *out, size_t cap) that opens path, reads up to cap bytes into out, then closes the file.

Input

  • path: filename of a file the grader writes in the working directory.
  • out / cap: destination buffer and the maximum number of bytes to read.

Output

Return the number of bytes actually read (0..cap). Return -1 if the file can't be opened or if path/out is NULL.

Example

file "rfb.bin" = "hello"
read_file_bytes("rfb.bin", out, 64)   ->   5   (out = "hello")
read_file_bytes("rfb.bin", out, 3)    ->   3   (out = "hel")
read_file_bytes("missing.bin", ...)   ->   -1

Edge cases

  • Missing file or NULL arg: -1.
  • Empty file: 0.
  • File larger than cap: read exactly cap bytes.

Rules

  • Use stdio (fopen/fread/fclose); always close before returning.

Why this matters

The first half of nearly every file tool: open, read up to a cap of bytes, close, report how many you got.

Input format

path: file to read. out/cap: buffer and max bytes.

Output format

long bytes read (0..cap), or -1 on open failure / NULL arg.

Constraints

Open in binary mode; a short read is not an error; always fclose.

Starter code

#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
long read_file_bytes(const char *path, unsigned char *out, size_t cap) {
    /* TODO */
    (void)path; (void)out; (void)cap;
    return -1;
}

Common mistakes

Leaking the FILE* on early return. Treating a short read as an error. Not checking fopen's NULL.

Edge cases to handle

Missing file → -1. Empty file → 0. cap smaller than the file → capped read.

Complexity

O(min(filesize, cap)).

Background lessons

Up next

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