linux-sysprog · intermediate · ~15 min
POSIX `open`/`read`/`write` (lower level than stdio).
Implement int cat_file(const char *path, int out_fd) that opens path and writes its full contents to out_fd. Return 0 on success and -1 on failure (e.g., open fails).
cat's inner loop — read bytes from stdin/files, write to stdout — is the foundation of every stream-processing tool. Implementing it right teaches you about short reads, EOF, and unbuffered I/O.
#include <fcntl.h>
#include <unistd.h>
int cat_file(const char *path, int out_fd) {
/* TODO */
return -1;
}
Reading fixed-size lines (cat preserves binary data — use fread/fwrite, not fgets). Stopping at the first 0 byte. Forgetting to fclose.
Empty file. Binary file with NUL bytes. Very large files (must stream — don't read into one giant buffer).
O(file size) time, O(buf size) memory.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.