linux-sysprog · intermediate · ~15 min
POSIX `open`/`read`/`write` (lower level than stdio).
Implement a tiny cat: open a file and write all of its bytes to a file descriptor using POSIX I/O.
Implement int cat_file(const char *path, int out_fd) that opens path for reading and writes its entire contents to out_fd. No main — the grader calls it.
path: the file to read.out_fd: an already-open writable file descriptor (e.g. a pipe or stdout).Returns 0 on success, -1 on failure (for example if open fails). All bytes of the file are written to out_fd.
file "data.txt" holds "the quick brown fox"
-> cat_file("data.txt", fd) returns 0; fd receives "the quick brown fox"
cat_file("nope.txt", 1) -> -1
-1.open/read/write (not stdio). Close the input fd before returning.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.
A file path and an already-open writable descriptor out_fd.
0 on success, -1 on failure; all file bytes written to out_fd.
Use POSIX open/read/write; handle short writes; close the input fd.
#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.