file-handling · intermediate · ~15 min
Use fread to pull raw bytes.
Read up to N bytes from the start of a file into a buffer.
Implement int read_first_bytes(const char *path, char *buf, int n) that reads up to n bytes from the file at path into buf and returns how many were actually read.
path: filename of a file the grader creates in the working directory.buf / n: destination buffer and the maximum number of bytes to read.Return the number of bytes read (0..n), or -1 if the file can't be opened.
file "rd_fixture.txt" = "hello"
read_first_bytes("rd_fixture.txt", buf, 3) -> 3 (buf = "hel")
read_first_bytes("missing", buf, 3) -> -1
n: returns the actual (smaller) count.fread with element size 1; open in binary mode; close before returning.path: file to read. buf/n: buffer and max bytes.
int bytes read (0..n), or -1 if the file can't be opened.
fread with element size 1; binary mode.
#include <stdio.h>
int read_first_bytes(const char *path, char *buf, int n) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.