file-handling · beginner · ~10 min
Open, bounded-read, and close a file safely.
#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).
fopen(path, "rb"); return -1 if it's NULL.fread(out, 1, cap, f) returns the count.fclose before returning.The first half of nearly every file tool: open, read up to a cap of bytes, close, report how many you got.
#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;
}
Leaking the FILE* on early return. Treating a short read as an error. Not checking fopen's NULL.
Missing file → -1. Empty file → 0. cap smaller than the file → capped read.
O(min(filesize, cap)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.