linux-sysprog · intermediate · ~15 min

Minimal cat: print file to fd

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

Challenge

Implement a tiny cat: open a file and write all of its bytes to a file descriptor using POSIX I/O.

Task

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.

Input

  • path: the file to read.
  • out_fd: an already-open writable file descriptor (e.g. a pipe or stdout).

Output

Returns 0 on success, -1 on failure (for example if open fails). All bytes of the file are written to out_fd.

Example

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

Edge cases

  • A missing/unopenable file returns -1.
  • Handle short writes by looping until the whole chunk is written.

Rules

  • Use POSIX open/read/write (not stdio). Close the input fd before returning.

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.

Input format

A file path and an already-open writable descriptor out_fd.

Output format

0 on success, -1 on failure; all file bytes written to out_fd.

Constraints

Use POSIX open/read/write; handle short writes; close the input fd.

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.