Skip to content
systemcoding.dev
Systems Programming

Read from stdin or a File Argument Like cat

Write a cat-style filter in C that reads the files named on the command line, uses standard input when there are none, and treats a lone hyphen as stdin.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and Linux logos.

cat notes.txt prints a file. cat with no arguments prints whatever you type, and producer | cat prints the output of another program. One tool, three behaviours, and the rule behind them is the same in every Unix filter: operands name files, and no operands means standard input. This post builds a small cat clone in C that follows that rule with read and write, handles the lone hyphen, reports errors per file and keeps going after a bad one. It is the input half of the guide to command-line tools in C, and the code runs on Linux with glibc 2.40 and on any POSIX system.

The rule in three sentences

POSIX describes it in the utility conventions and in the text of each filter, and it comes down to three sentences. If no file operands are given, the utility reads standard input. If an operand is a single hyphen, the utility reads standard input at that point in the sequence. Otherwise, the operand is a path name, opened for reading in the order given.

The consequence for design is that a filter should be written around file descriptors, not file names. A function that copies from descriptor in to descriptor 1 works for a file you just opened, for a pipe, for a terminal and for a socket. The only place that cares about the difference is the loop in main that decides which descriptor to hand it.

Copying with read and write

The core is a loop that reads a block and writes the block, handling short writes and interrupted calls. A write to a pipe or terminal may transfer fewer bytes than requested, and a signal can interrupt either call, so both need small loops.

copy.cc
#include <errno.h>
#include <unistd.h>

#define BUFSZ 65536

int copy_fd(int in, int out)
{
    static char buf[BUFSZ];

    for (;;) {
        ssize_t n = read(in, buf, sizeof buf);
        if (n < 0) {
            if (errno == EINTR)
                continue;
            return -1;
        }
        if (n == 0)
            return 0;

        char *p = buf;
        while (n > 0) {
            ssize_t w = write(out, p, (size_t)n);
            if (w < 0) {
                if (errno == EINTR)
                    continue;
                return -2;
            }
            p += w;
            n -= w;
        }
    }
}

The function returns 0 at end of input, -1 for a read error and -2 for a write error. The distinction matters, because a failed read is the fault of one input, while a failed write means the output has gone, usually a closed pipe or a full disk, and there is no point in continuing with the other files. The buffer is static to keep a 64 KiB array off the stack, which is safe here because the function is not reentrant and the program has one thread.

Choosing the descriptor

The loop over operands decides what each name means. A hyphen maps to descriptor 0 and is never closed. Anything else is opened, copied and closed.

mycat.cc
#define _GNU_SOURCE
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int copy_fd(int in, int out);

static int cat_operand(const char *name)
{
    int fd;

    if (strcmp(name, "-") == 0) {
        fd = STDIN_FILENO;
    } else {
        fd = open(name, O_RDONLY | O_CLOEXEC);
        if (fd < 0) {
            warn("%s", name);
            return -1;
        }
    }

    int rc = copy_fd(fd, STDOUT_FILENO);
    int saved = errno;

    if (fd != STDIN_FILENO)
        close(fd);

    if (rc == -1) {
        errno = saved;
        warn("%s", name);
        return -1;
    }
    if (rc == -2) {
        errno = saved;
        err(1, "write error");
    }
    return 0;
}

int main(int argc, char *argv[])
{
    int status = 0;

    if (argc == 1) {
        if (cat_operand("-") != 0)
            status = 1;
    } else {
        for (int i = 1; i < argc; i++)
            if (cat_operand(argv[i]) != 0)
                status = 1;
    }
    return status;
}

The errno handling is a detail that bites. close can overwrite errno, so the code saves it right after copy_fd returns and restores it before calling warn. Without that, a read error on a directory could print the wrong reason.

With a file a.txt containing alpha and a file b.txt containing beta, each ending in a newline, the cases behave like this:

Text
$ ./mycat a.txt b.txt
alpha
beta
$ printf 'from pipe\n' | ./mycat a.txt - b.txt
alpha
from pipe
beta
$ ./mycat a.txt missing.txt b.txt
alpha
./mycat: missing.txt: No such file or directory
beta
$ echo $?
1

The second command shows the hyphen in the middle of the list, where standard input is read at that position. The third shows the keep-going rule: the failure is reported on standard error, the tool carries on with b.txt and the final status is 1.

Why a write error stops everything

When write fails, the tool calls err, which prints the message and exits with status 1 without going on to the other operands. The reason is that every later write would fail the same way. The most common cause is EPIPE, which arises when the reader of the pipe has gone away, as in mycat huge.log | head -1. In that case the kernel sends SIGPIPE first, whose default action ends the process before the write call returns. The explicit check matters when SIGPIPE is ignored or blocked, which the parent shell can arrange, or when the cause is a different error such as ENOSPC for a full disk. The two cases together are why pipelines need attention to buffering and SIGPIPE.

Detecting the same file for input and output

A trap in this style of tool is mycat a.txt b.txt > a.txt. The shell truncates a.txt before the program starts, so mycat reads an empty file and writes nothing, and the original contents are gone. GNU cat detects the case when standard output is a regular file that is also one of the inputs, and prints input file is output file. It compares the device and inode numbers from fstat:

c
struct stat in_st, out_st;
if (fstat(fd, &in_st) == 0 && fstat(STDOUT_FILENO, &out_st) == 0
    && S_ISREG(out_st.st_mode)
    && in_st.st_dev == out_st.st_dev && in_st.st_ino == out_st.st_ino) {
    warnx("%s: input file is output file", name);
    close(fd);
    return -1;
}

Insert it after the open. In the truncation case the shell has already emptied the file, so the data cannot be saved, but the check turns a silent loss into an error message the user can read. In the append case, mycat a.txt >> a.txt, the check prevents a worse outcome: without it the tool reads the file it is growing and never reaches the end, until the disk fills. A tool that copies many files benefits from the same guard.

Directories, special files and errors on read

open(".", O_RDONLY) succeeds on Linux, and the first read fails with EISDIR. The warn call prints mycat: .: Is a directory, which is the same message GNU cat gives, so the code above needs no special case. Special files work as inputs: mycat /dev/null prints nothing, and mycat /proc/version prints the kernel version because /proc files are read through the same interface.

Reading from a terminal needs one more note. When standard input is a terminal, read returns after each line the user types, and a Ctrl-D at the start of a line makes read return 0, which the loop treats as end of input. A second Ctrl-D is not needed. If you named - twice, mycat - -, the second read would also see the terminal: it asks the user for more input after the first end of file, which is how GNU cat behaves as well.

Buffering choices

This tool uses read and write directly with a large buffer, and it skips stdio entirely. That is the right choice for a copy, because stdio would add a second buffer and a second copy of every byte. If you do use fread and fwrite, you get portability across systems and platforms at the cost of that extra step. If you use getchar and putchar in a loop, the program works and is much slower per byte, because each call goes through the library's locking and buffer logic. A modern kernel interface exists for the pure copy case, copy_file_range and sendfile, but they require a regular file on the input side and a particular kind of output, so a cat-style tool that accepts pipes and terminals keeps the plain loop.

What this version leaves out

The real cat has options this clone does not: -n to number lines, -A to show non-printing characters and -s to squeeze blank lines. Each of them needs the program to look at the bytes, which means a different inner loop and the buffering questions that come with it. A line-numbering variant has to track whether it is at the start of a line across block boundaries, in the same way the word counter in the guide tracks whether it is inside a word. The structure of main, the operand loop and the error handling stays the same, which is the argument for writing filters this way.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.