file-handling · beginner · ~10 min
Open, bounded-read, and close a file safely.
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.
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.
path: filename of a file the grader writes in the working directory.out / cap: destination buffer and the maximum number of bytes to read.Return the number of bytes actually read (0..cap). Return -1 if the file can't be opened or if path/out is NULL.
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
cap: read exactly cap bytes.fopen/fread/fclose); always close before returning.The first half of nearly every file tool: open, read up to a cap of bytes, close, report how many you got.
path: file to read. out/cap: buffer and max bytes.
long bytes read (0..cap), or -1 on open failure / NULL arg.
Open in binary mode; a short read is not an error; always fclose.
#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.