linux-sysprog · intermediate · ~15 min

Minimal cat: print file to fd

POSIX `open`/`read`/`write` (lower level than stdio).

Challenge

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).

Why this matters

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.

Starter code

#include <fcntl.h>
#include <unistd.h>

int cat_file(const char *path, int out_fd) {
    /* TODO */
    return -1;
}

Common mistakes

Reading fixed-size lines (cat preserves binary data — use fread/fwrite, not fgets). Stopping at the first 0 byte. Forgetting to fclose.

Edge cases to handle

Empty file. Binary file with NUL bytes. Very large files (must stream — don't read into one giant buffer).

Complexity

O(file size) time, O(buf size) memory.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.