file-handling · beginner · ~10 min

Read a file into a bounded buffer

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

Challenge

Your job

#include <stdint.h>
#include <stddef.h>
long read_file_bytes(const char *path, unsigned char *out, size_t cap);

Open path, read up to cap bytes into out, close. Return the number of bytes read, or -1 if the file can't be opened (or any arg is NULL).

Hints

  1. fopen(path, "rb"); return -1 if it's NULL.
  2. fread(out, 1, cap, f) returns the count.
  3. Always fclose 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.

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.