Skip to content
systemcoding.dev
Systems Programming

The Complete Guide to Building Command-Line Tools in C

Build a real Unix command-line tool in C from argument parsing to exit codes, pipelines, locale, tests and a man page, with every step explained.

27 min read
Summarize in AI
Flat illustration of a terminal session, with the C, Linux and GNU Bash logos.

A command-line tool is a small contract between a program and everything around it: the shell that starts it, the files and pipes it reads and writes, the scripts that call it and the people who type its name. A tool that honours that contract composes with every other tool on the system, and a tool that breaks it gets wrapped in workarounds. This guide builds one complete tool in C, step by step, and uses it to explain each part of the contract: arguments, options, input, output, errors, exit codes, signals, buffering, locale, testing and installation. The tool is called lcount, a cut-down wc, and by the end you will have a program you can read in one sitting and a checklist you can apply to any other tool.

The code targets C11 on Linux with glibc 2.40 and GCC 14, and sticks to interfaces specified in POSIX.1-2024 unless the text says otherwise. Where glibc, musl and the BSDs differ, the difference is named. The guide is the hub for the command-line tools cluster, so the later posts on getopt, getopt_long, exit codes, reading stdin or a file, error output and line reading each take one section of it further.

What the contract is

Before writing code, name the parts of the contract. A Unix tool receives four things from its parent and gives back three.

ReceivedWhere it arrivesExample
Argumentsargc and argvlcount -l notes.txt
Standard inputdescriptor 0the output of the previous command in a pipeline
Environmentenviron, getenvLANG, TMPDIR, NO_COLOR
SignalsasynchronousSIGINT from Ctrl-C, SIGPIPE from a closed reader
Given backWhere it goesExample
Standard outputdescriptor 1the counts, and nothing else
Standard errordescriptor 2diagnostics for a human
Exit statusexit or return from main0 for success, nonzero for failure

The discipline that makes tools composable is to keep the three outputs separate. Results go to standard output so that a pipeline can feed them to the next program. Messages meant for a person go to standard error, so that a pipeline does not corrupt its data stream with a complaint. And the exit status says whether it worked, so that if, && and set -e in a script can react without parsing text.

Everything in this guide follows from that separation.

The smallest program and what main receives

A tool starts at main. The two-parameter form is the one that matters:

hello.cc
#include <stdio.h>

int main(int argc, char *argv[])
{
    for (int i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);
    return 0;
}

Run as ./hello -l "two words" file.txt, it prints:

Text
argv[0] = "./hello"
argv[1] = "-l"
argv[2] = "two words"
argv[3] = "file.txt"

Three facts follow from this. First, argv[0] is whatever the parent chose to put there, usually the path used to run the tool. It is not a reliable program name, but it is the conventional one for usage messages. Second, the shell did the splitting: "two words" arrived as one argument because the shell removed the quotes, and the program never sees them. Third, argv[argc] is a null pointer, so a loop that walks until NULL is also correct.

Return from main and exit are equivalent: return n; from main calls exit(n), which flushes standard I/O and runs atexit handlers. The low-level _exit skips both, and is for a child process after fork.

Arguments, options and operands

POSIX gives the pieces names, in the Utility Conventions chapter of the Base Definitions. An option is an argument beginning with a hyphen followed by a letter, such as -l. An option-argument is the value an option takes, as in -o out.txt. An operand is everything else, usually a file name. A lone -- ends option processing, so lcount -- -l treats -l as a file called -l. A lone - is conventionally an operand meaning standard input.

Several short options may be bundled (-lw is -l -w), and an option with a value may attach it (-ofile) or separate it (-o file). GNU tools add long options such as --lines, with --lines=5 or --lines 5. You could parse all of that by hand, and many people do, and get the corner cases wrong. The C library already contains a correct parser.

Parsing short options with getopt

getopt is declared in <unistd.h>. You call it in a loop, giving the option string, and it returns each option character in turn. The string lists the valid option letters, and a colon after a letter means the option takes a value.

getopt_demo.cc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int opt;
    int lines = 0, words = 0, bytes = 0;

    while ((opt = getopt(argc, argv, "lwc")) != -1) {
        switch (opt) {
        case 'l': lines = 1; break;
        case 'w': words = 1; break;
        case 'c': bytes = 1; break;
        default:
            fprintf(stderr, "usage: %s [-lwc] [file ...]\n", argv[0]);
            return 2;
        }
    }

    printf("l=%d w=%d c=%d, operands start at %d\n", lines, words, bytes, optind);
    for (int i = optind; i < argc; i++)
        printf("operand: %s\n", argv[i]);
    return 0;
}

With ./getopt_demo -lw notes.txt log.txt the output is:

Text
l=1 w=1 c=0, operands start at 2
operand: notes.txt
operand: log.txt

The global optind is the index of the first argument getopt did not consume, so the operands are argv[optind] through argv[argc - 1]. When getopt meets an unknown option it prints a message to standard error itself (invalid option -- 'x') and returns ?. Set the external variable opterr to 0 to silence that message if you prefer your own. See getopt(3).

One behaviour differs between systems. glibc permutes the arguments by default, so ./tool file.txt -l still sees -l as an option. POSIX does not allow that: option parsing stops at the first operand. glibc follows POSIX when the environment variable POSIXLY_CORRECT is set, or when the option string starts with +. BSD and musl stop at the first operand. A script that works on glibc by passing options after file names then fails elsewhere, so tools meant to be portable write options first.

Long options with getopt_long

Long options need getopt_long, declared in <getopt.h>. It takes a table of struct option entries, each with the name, whether it takes an argument, an optional flag pointer and the value to return.

long_table.cc
#include <getopt.h>

static const struct option long_options[] = {
    { "lines",   no_argument, NULL, 'l' },
    { "words",   no_argument, NULL, 'w' },
    { "bytes",   no_argument, NULL, 'c' },
    { "help",    no_argument, NULL, 'h' },
    { "version", no_argument, NULL, 'V' },
    { NULL, 0, NULL, 0 }
};

Each long option maps to the same character as its short twin, so the switch statement needs no extra cases. The table ends with an all-zero entry. The call becomes getopt_long(argc, argv, "lwcVh", long_options, NULL). The glibc implementation also accepts unambiguous abbreviations, so --byt matches --bytes. That is convenient interactively and a trap in scripts, because adding a new option such as --byte-order later turns the abbreviation into an ambiguity. Scripts should use full names.

getopt_long is a GNU extension, but it exists on musl, FreeBSD, OpenBSD, NetBSD and macOS with the same interface. It is not in POSIX.1-2024. If you need strict portability, stay with getopt.

Operands: files, and standard input as the default

A filter tool reads the files named on its command line, and reads standard input when there are none. That one rule is what makes lcount file and producer | lcount both work. The structure is a loop over operands, with a branch for the empty case, and a special name for standard input.

operands.cc
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int process_file(const char *name);
int process_fd(int fd, const char *name);

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

    if (first >= argc)
        return process_fd(STDIN_FILENO, NULL);

    for (int i = first; i < argc; i++) {
        if (argv[i][0] == '-' && argv[i][1] == '\0') {
            if (process_fd(STDIN_FILENO, "-") != 0)
                status = 1;
        } else if (process_file(argv[i]) != 0) {
            status = 1;
        }
    }
    return status;
}

Two decisions are visible. A failure on one file does not stop the others: the loop records the failure in status and goes on, as wc, cat and grep do. And the function returns a status that main converts into the exit code. A tool that exits at the first bad file is easier to write and worse to use, since the user runs it again to discover the second bad file.

Counting with read

For a counting tool the right primitive is read(2) into a buffer, not getchar in a loop. The system call transfers a block, and the loop over the block runs in your code with no per-character function call. A 64 KiB buffer is a reasonable size on Linux. It is large enough to make system calls rare and small enough to stay in cache. There is no measurement behind the number here, and a tool that cares should measure on its own workload, but the mechanism is sound: fewer system calls per megabyte.

count.cc
#include <ctype.h>
#include <errno.h>
#include <unistd.h>

struct counts {
    unsigned long long lines, words, bytes;
};

int count_fd(int fd, struct counts *c)
{
    unsigned char buf[65536];
    int in_word = 0;

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

        c->bytes += (unsigned long long)n;
        for (ssize_t i = 0; i < n; i++) {
            if (buf[i] == '\n')
                c->lines++;
            if (isspace(buf[i])) {
                in_word = 0;
            } else if (!in_word) {
                in_word = 1;
                c->words++;
            }
        }
    }
}

Four details deserve attention. The buffer is unsigned char, because passing a negative char to isspace is undefined behaviour: the <ctype.h> functions take an int that must be EOF or a value representable as unsigned char. The in_word state lives outside the loop, so a word that straddles two reads is counted once. The EINTR check retries a read that a signal handler interrupted. And end of file is read returning zero, which is the normal exit from the loop, while a negative return is an error that the caller reports with errno intact.

For a text file whose content is one two newline three newline, the counts are 2 lines, 3 words and 14 bytes: eight bytes in the first line, including the newline, and six in the second.

Opening files and reporting why they failed

process_file opens the named file, counts it and closes it, and it is where most error paths live.

file.cc
#include <err.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

struct counts;
int count_fd(int fd, struct counts *c);
void report(const struct counts *c, const char *name);

int process_fd(int fd, const char *name)
{
    struct counts c = { 0, 0, 0 };

    if (count_fd(fd, &c) < 0) {
        warn("%s", name ? name : "stdin");
        return -1;
    }
    report(&c, name);
    return 0;
}

int process_file(const char *name)
{
    int fd = open(name, O_RDONLY | O_CLOEXEC);
    if (fd < 0) {
        warn("%s", name);
        return -1;
    }

    struct stat st;
    if (fstat(fd, &st) == 0 && S_ISDIR(st.st_mode)) {
        warnx("%s: is a directory", name);
        close(fd);
        return -1;
    }

    int rc = process_fd(fd, name);
    close(fd);
    return rc;
}

warn and warnx come from <err.h>, a BSD interface that glibc and musl both provide. warn prints the program name, the formatted message and the text of errno, in the form lcount: missing.txt: No such file or directory. warnx prints the same without the errno text. They write to standard error and do not exit, unlike err and errx, which print and then call exit. The details are in writing errors to stderr. The directory check is there because open on a directory with O_RDONLY succeeds on Linux, and read then fails with EISDIR. Checking up front gives a clearer message and the same behaviour as wc.

The program name in those messages comes from argv[0]. glibc's warn uses program_invocation_short_name, which is the basename of argv[0], so /usr/local/bin/lcount is shown as lcount. The BSD err family uses getprogname(). Either way you never format the prefix by hand.

Printing the result

Output formatting follows wc: each selected count right-aligned in a column of width 7, separated by a space, followed by the file name if there is one.

report.cc
#include <stdio.h>

struct counts {
    unsigned long long lines, words, bytes;
};

extern int want_lines, want_words, want_bytes;

void report(const struct counts *c, const char *name)
{
    int first = 1;

    if (want_lines) {
        printf("%7llu", c->lines);
        first = 0;
    }
    if (want_words) {
        printf("%s%7llu", first ? "" : " ", c->words);
        first = 0;
    }
    if (want_bytes) {
        printf("%s%7llu", first ? "" : " ", c->bytes);
    }
    if (name)
        printf(" %s", name);
    putchar('\n');
}

For the two-line text above and with all three counts selected, a pipe feeding standard input prints a line with no name, and a file argument prints it with one:

Text
      2       3      14
      2       3      14 notes.txt

The unsigned 64-bit type avoids overflow for any file a machine can hold. Using %llu with unsigned long long is the portable way to print it, and a cast is needed if you choose uint64_t, because the PRIu64 macro is the right format for that type.

Exit codes

The exit status is a number from 0 to 255 that the parent reads with $? or waitpid. Zero means success. Everything else means some kind of failure, and the convention for what each value means is thin but real.

CodeConventional meaning
0Success
1General failure, such as a file that could not be read
2Usage error: bad option, missing operand
126Command found but not executable (shell convention)
127Command not found (shell convention)
128 + nKilled by signal n (shell convention)

lcount uses 0, 1 and 2. A usage error returns 2 so that a script can tell "you called me wrong" from "the data was bad", which is how grep and many GNU tools behave. Exit codes and conventions for Unix tools covers sysexits.h and the cases where other numbers help.

Do not return the raw value of errno as an exit status. It is not portable between systems, it can exceed 255, and the parent cannot map it back to a meaning. Use EXIT_SUCCESS and EXIT_FAILURE from <stdlib.h> for the two portable values, and named constants for any others.

Putting main together

With the pieces in place, main becomes short. It sets up options, calls the operand loop and converts the result.

main.cc
#define _GNU_SOURCE
#include <err.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int want_lines, want_words, want_bytes;

int process_operands(int argc, char *argv[], int first);

static void usage(FILE *out)
{
    fprintf(out, "usage: lcount [-lwc] [--] [file ...]\n");
    fprintf(out, "  -l, --lines    count lines\n");
    fprintf(out, "  -w, --words    count words\n");
    fprintf(out, "  -c, --bytes    count bytes\n");
    fprintf(out, "  -h, --help     show this help\n");
    fprintf(out, "  -V, --version  show the version\n");
}

int main(int argc, char *argv[])
{
    static const struct option long_options[] = {
        { "lines",   no_argument, NULL, 'l' },
        { "words",   no_argument, NULL, 'w' },
        { "bytes",   no_argument, NULL, 'c' },
        { "help",    no_argument, NULL, 'h' },
        { "version", no_argument, NULL, 'V' },
        { NULL, 0, NULL, 0 }
    };
    int opt;

    while ((opt = getopt_long(argc, argv, "lwcVh", long_options, NULL)) != -1) {
        switch (opt) {
        case 'l': want_lines = 1; break;
        case 'w': want_words = 1; break;
        case 'c': want_bytes = 1; break;
        case 'h':
            usage(stdout);
            return EXIT_SUCCESS;
        case 'V':
            puts("lcount 1.0");
            return EXIT_SUCCESS;
        default:
            usage(stderr);
            return 2;
        }
    }

    if (!want_lines && !want_words && !want_bytes)
        want_lines = want_words = want_bytes = 1;

    int status = process_operands(argc, argv, optind);

    if (fflush(stdout) != 0 || ferror(stdout))
        err(EXIT_FAILURE, "write error");

    return status;
}

The --help text goes to standard output and exits 0, because the user asked for it, and a pipe to less should work. The usage shown after an error goes to standard error and exits 2. The GNU Coding Standards ask for exactly that behaviour, and --version printing one line and exiting 0 is the other standard request.

The final fflush and ferror check matters more than it looks. Standard output is buffered, and a write failure such as a full disk or a closed pipe may not show up until the buffer is flushed at exit. If you ignore the result, the tool exits 0 after losing its output. Checking at the end, and reporting a write error, makes the failure visible. A printf return value check on every call is noise by comparison.

A session with the finished tool looks like this:

Text
$ printf 'one two\nthree\n' | lcount
      2       3      14
$ lcount -w notes.txt missing.txt
      3 notes.txt
lcount: missing.txt: No such file or directory
$ echo $?
1
$ lcount -x
lcount: invalid option -- 'x'
usage: lcount [-lwc] [--] [file ...]
...
$ echo $?
2

The first line of output for -x is getopt's own message, which it writes because opterr is still 1. The usage text follows. The exit status 2 distinguishes it from the file error above it.

Pipelines: buffering and SIGPIPE

A tool in a pipeline does not know its neighbours, but two kernel behaviours affect it directly.

The first is buffering. The C library chooses the buffering of stdout at the first write: line buffered if it is a terminal, fully buffered otherwise. In a pipeline, output stays in the buffer until it fills (typically 4096 or 8192 bytes, and glibc uses the file's block size) or the program exits. A tool that prints a result per input line and is meant to be used with tail -f or interactively needs fflush(stdout) after each line, or setvbuf(stdout, NULL, _IOLBF, 0) at startup. lcount prints once at the end, so the default is right. Making a tool work in pipelines goes through the cases.

The second is SIGPIPE. If the reader at the other end of the pipe exits, as in lcount big.log | head -1, the next write to the pipe makes the kernel send SIGPIPE, whose default action kills the writer. For most filters that default is exactly right: the process dies quietly and the pipeline shuts down. Do not ignore SIGPIPE unless you are ready to handle EPIPE from every write, or the tool will print Broken pipe errors where a silent exit was the expected behaviour. A long-running service is the case where ignoring it is correct.

Environment and locale

A well-behaved tool reads a small set of environment variables and ignores the rest.

  • TMPDIR names where temporary files go. Fall back to /tmp.

  • NO_COLOR, when set to any non-empty value, asks for no colour in output. See the convention at no-color.org.

  • LANG, LC_ALL and LC_CTYPE select the locale that classifies characters.

  • POSIXLY_CORRECT changes how glibc's getopt treats operands.

The locale matters for character classification. isspace in the default "C" locale recognises only the six ASCII white-space characters. A program that calls setlocale(LC_ALL, "") at the start of main adopts the user's locale, and then isspace follows it. For UTF-8 text with multibyte characters, counting characters rather than bytes needs mbrtowc or the isw* family, and the details are in handling locale and UTF-8 input. lcount counts bytes and white-space separated words in the C locale, which is stated in its help and is the same answer for every user.

Reading getenv returns a pointer into the environment block, so copy the string if you will modify the environment later. And never trust an environment variable as a path to execute without validating it, because the caller of a setuid program controls it.

Signals the tool should expect

A short-lived filter rarely handles signals, and the defaults are right: SIGINT from Ctrl-C ends it, and the shell reports status 130. A tool that creates temporary or partial output files must clean them up, and the pattern is in making your tool crash-safe: write to a temporary name in the destination directory, then rename it into place when complete, and remove it from a handler for SIGINT and SIGTERM.

The rule for handlers is strict. Inside a signal handler only async-signal-safe functions may be called, a short list in signal-safety(7). printf, malloc and free are not on it. The reliable handler sets a volatile sig_atomic_t flag and returns, and the main loop checks it. A read interrupted by the signal returns EINTR, and the count_fd loop above would retry it, so a handler that wants to stop the loop sets the flag and the loop tests it on EINTR.

Testing a tool without a framework

A command-line tool is easy to test because its interface is text in and text out. A shell script can drive it and compare against expected output with cmp or diff.

test.shShell
#!/bin/sh
set -u
fail=0

check() {
    desc=$1; want=$2; got=$3
    if [ "$want" != "$got" ]; then
        echo "FAIL: $desc"
        echo "  want: $want"
        echo "  got:  $got"
        fail=1
    fi
}

check "stdin counts" "      2       3      14" \
    "$(printf 'one two\nthree\n' | ./lcount)"

check "lines only" "      2" \
    "$(printf 'a\nb\n' | ./lcount -l)"

check "words only, long option" "      3" \
    "$(printf 'a b\nc\n' | ./lcount --words)"

./lcount missing.txt 2>/dev/null
check "missing file exits 1" 1 "$?"

./lcount -x 2>/dev/null
check "bad option exits 2" 2 "$?"

exit $fail

Running sh test.sh prints nothing when every check passes and exits 0, which is the convention for tests: silence means success. A failing check prints the description and both values. The script uses set -u to catch typos in variable names, quotes every expansion, and tests exit codes explicitly, since those are part of the contract.

Add the edge cases that bite in practice: an empty file (counts all zero), a file with no trailing newline (the last word still counts, the last line does not), a file with a NUL byte (bytes counts it), and a very large file, which exercises the unsigned long long counters and the chunk boundary logic.

Compile with warnings and a sanitizer while you test. gcc -std=c11 -Wall -Wextra -Wpedantic -O2 -g -fsanitize=address,undefined -o lcount main.c count.c file.c report.c turns most memory and undefined-behaviour mistakes into immediate crashes with a stack trace. Keep a separate release build without the sanitizers, since they change performance and link a runtime.

Building and installing

For a four-file tool a Makefile is enough, and it documents the build for the next person.

Makefilemake
CC      ?= cc
CFLAGS  ?= -std=c11 -O2 -g -Wall -Wextra -Wpedantic
PREFIX  ?= /usr/local

SRC = main.c count.c file.c report.c
OBJ = $(SRC:.c=.o)

lcount: $(OBJ)
	$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJ)

install: lcount
	install -D -m 0755 lcount $(DESTDIR)$(PREFIX)/bin/lcount
	install -D -m 0644 lcount.1 $(DESTDIR)$(PREFIX)/share/man/man1/lcount.1

clean:
	rm -f lcount $(OBJ)

.PHONY: install clean

Three conventions in that file are worth keeping. The ?= assignments let the user override CC, CFLAGS and PREFIX from the environment or the command line, which packagers rely on. DESTDIR is prepended to every install path so that a package build can stage the files in a temporary tree. And install -D creates the destination directories. Keeping $(LDFLAGS) on the link line and $(CFLAGS) in both places follows the standard variable names, so hardening flags added by a distribution take effect.

The manual page is a file in man(7) format, and without one the tool has no documentation that man lcount can find. Installing man pages and shell completions covers the format, and a static binary for distribution is the subject of building a static CLI binary with musl.

Portability: glibc, musl and the BSDs

The tool as written builds on glibc, musl and the BSDs, with these known differences.

ItemglibcmuslBSD and macOS
err.h and warnYesYesYes
getopt_longYesYesYes
getopt argument permutationYes, unless POSIXLY_CORRECT or leading +NoNo
O_CLOEXECYesYesYes

The one behaviour that needs a decision is getopt permutation. If you want the same parsing everywhere, start the option string with +, as in "+lwcVh". glibc then stops at the first operand like the others. For GNU-style tools that is a regression for users who put options last, so the choice is a policy one: strict POSIX or friendly GNU.

On Windows, none of this applies unchanged. There is no getopt in the Microsoft C runtime, the console has no process groups, and file names use another encoding. Portable tools that must run there use a library or compile with MinGW, which ships getopt.

Designing options people can remember

The parsing library decides how options are read, and you decide which options exist. Most of the long-term cost of a tool is in that second decision, because a published option is a promise that scripts will depend on.

Follow the names that users already know. -v is verbose in most tools, but it is version in a few and invert-match in grep, so prefer -V or --version for the version and keep -v for verbosity if you offer it at all. -q means quiet, -n means dry run in tools influenced by make and line numbers in others, -f takes a file, -o takes an output file, -r or -R means recursive, and -h is help in most places and human-readable sizes in ls and df. When your tool collides with a convention, pick the long name that cannot be misread and make the short one optional.

Give every short option a long twin, because scripts should use the long form for readability and the short form is for typing. Make boolean options positive: --color and --no-color read better than a flag named --disable-color-output. Avoid options whose meaning flips with another option, because the combination space grows faster than anyone tests it. And never make an option's effect depend on its position among the others unless POSIX says so, since a user reading a command cannot see the order of evaluation.

Treat the set of options as an API. Removing an option breaks scripts silently or loudly, so deprecate it first: keep accepting it, print a warning to standard error, and say what replaces it. A tool that renames options between releases teaches its users to pin versions.

Interactive and non-interactive use

The same binary runs under a person at a terminal and under a script with no terminal. The call that tells them apart is isatty(STDOUT_FILENO), declared in <unistd.h>, and it returns 1 when descriptor 1 is a terminal. Behaviour that should follow it includes colour, progress bars and prompts.

Colour is the common case. Print escape sequences only when standard output is a terminal, when NO_COLOR is not set and when TERM is not dumb. A tool that writes colour into a pipe corrupts the next program's input, and grep --color=auto is the model: the auto value defers to isatty, while always and never let the user override it.

Progress output belongs on standard error, so that it never mixes with data on standard output, and it should appear only if standard error is a terminal. A tool that asks a question must read the answer from the terminal and fail clearly, not hang, when there is none. The safe pattern is to refuse to prompt when isatty(STDIN_FILENO) is false and to tell the user which option answers the question in advance, such as --yes.

A last interactive detail is the terminal width. ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) returns the size when output is a terminal. Tools that format columns read it and fall back to 80 when it fails. Treat a width of zero, which a freshly created pty can report, as unknown.

Reading input line by line

lcount counts bytes in fixed chunks, which is right for counting. Many tools need whole lines: filtering, searching, transforming. The primitive is getline, declared in <stdio.h> and specified in POSIX.1-2008 and later. It reads one line of any length into a buffer it allocates and grows for you, which removes the fixed-size fgets buffer and its truncation problem. The next function filters lines containing a fixed string and numbers them, which is the core of a simple grep -n.

grepn.cc
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s pattern < input\n", argv[0]);
        return 2;
    }

    char *line = NULL;
    size_t cap = 0;
    ssize_t len;
    unsigned long n = 0;
    int found = 0;

    while ((len = getline(&line, &cap, stdin)) != -1) {
        n++;
        if (strstr(line, argv[1]) != NULL) {
            printf("%lu:%s", n, line);
            found = 1;
        }
    }
    free(line);

    if (ferror(stdin)) {
        perror("read error");
        return 2;
    }
    return found ? 0 : 1;
}

Given input of alpha, beta and alphabet on three lines and the pattern alpha, the output is:

Text
1:alpha
3:alphabet

The exit code follows grep: 0 if something matched, 1 if nothing did, 2 on error. That choice makes the tool usable in an if statement, and it shows why 1 is better kept for "no match" in a search tool and for failure in a counting tool. The convention is part of each tool's contract, so document it.

Three details of getline matter. The returned length includes the newline, so a final line with no newline is returned without one, and printing it with "%s" omits the trailing newline faithfully. The buffer pointer and capacity are reused across calls, so the allocation is amortised, and you free it once at the end. And the function returns -1 for both end of file and error, so check ferror afterwards, as the code does. A line longer than memory fails with ENOMEM, so a tool that reads untrusted input should cap the line length, which getline itself does not do.

An embedded NUL byte in a line is where strstr stops working: the string functions treat the NUL as the end. getline returns the length, so a tool that must handle binary data uses memmem or its own search over the length, not the C string functions.

Configuration: flags, environment, files

A tool with more than a handful of options eventually wants defaults. The order of precedence that users expect is fixed by long practice: command-line flags win over environment variables, which win over a per-user configuration file, which wins over a system file, which wins over the built-in default. Documenting the order in the manual is as important as implementing it.

Keep the machinery small. An environment variable named after the tool, such as LCOUNT_OPTS, is a one-line addition, and a file in $XDG_CONFIG_HOME/lcount/config with a fallback to $HOME/.config/lcount/config follows the XDG Base Directory Specification. Parse it with the same code path as the command line, so the file is just a list of options, and there is one grammar to test and document. Do not invent a configuration language for a tool with four options.

Resource limits and robustness

A filter that reads from a pipe has no idea how large its input is. Two limits are worth setting deliberately. The first is memory: any buffer sized from input must have a ceiling, and the tool must fail with a message and a nonzero status when it is exceeded, not exhaust memory. The second is descriptor leaks: a tool that opens many files in a loop must close each one, and lcount does, because the process limit on open files is typically 1024 and ulimit -n shows it for the current shell.

Check every allocation. On Linux with default overcommit, malloc rarely returns NULL, and the process is killed later instead, but a tool that runs inside a container with a memory limit or under ulimit -v does see it fail. The cost of an if (!p) is a line, and err(EXIT_FAILURE, "malloc") is a fine response for a tool that cannot continue.

When a C tool is the wrong choice

C earns its place for a tool that is tiny, starts fast, has no runtime to install and handles bytes directly. It is the wrong choice in several situations, and saying so is part of the guide.

  • The work is mostly text parsing and string building. In C every string is a buffer with a length you must track. A shell, Python or Awk script finishes the task faster and with fewer memory errors.

  • The tool talks to networks or formats with deep libraries. JSON, TLS and HTTP are one dependency in Go or Rust. In C they are a dependency plus an ownership model to get right.

  • The tool must run safely on untrusted input. A parser for hostile files is where memory-safety bugs are paid for. Rust, Go or a sandboxed process reduce that risk.

  • Many people will contribute. The review cost of C pointer code is higher than that of languages with bounds checks.

For a counting tool, a cat clone or a utility that is mostly system calls, C is a good fit, and the discipline above is what makes it a pleasant one. The same tool in other languages is covered in a CLI tool in Go with exit codes and signals, a Unix filter in Zig and clean Rust CLI output.

Writing messages that people can act on

A message is the only part of the program a stressed person reads, so it carries a disproportionate share of the tool's usability. A good error message answers three questions: what failed, on which object, and why. The warn call produces that shape without effort: the program name says who is speaking, the file name says which object, and the errno text says why. A message such as lcount: report.txt: Permission denied needs no explanation. A message such as error: operation failed needs a debugger.

Keep each message on one line and start it with the program name, because logs and terminals interleave output from many programs. Do not end with a full stop or an exclamation mark, do not shout in capitals, and do not print stack-like noise for expected conditions. Reserve extra detail for a verbose flag. Messages should be stable too, since scripts and bug reports quote them, and changing wording is a compatibility decision.

The help text follows the same rule. Put a one-line synopsis first, then one line per option with the short and long forms aligned, then a sentence on operands and exit codes. Keep it under a screen. Long explanations belong in the manual page, and the help text should end with a pointer to it. If a user types the tool's name with no arguments and standard input is a terminal, the tool should not sit silently waiting for input: it should print the usage and exit with status 2, which turns a confusing hang into a hint.

Localisation is the last consideration. Tools that translate their messages with gettext keep the program name and the errno text translatable, and they mark every user-visible string at the call site. For a tool with a technical audience, English messages that never change are an acceptable and consistent choice, and mixing translated messages with untranslated option names is worse than either.

A checklist for any tool you ship

Run through this before calling a tool finished.

  1. It prints results to standard output and messages to standard error.

  2. It returns 0 on success, 1 on runtime failure and 2 on a usage error, and says so in its manual.

  3. --help prints usage to standard output and exits 0, and --version prints one line and exits 0.

  4. It accepts -- and treats - as standard input where that makes sense.

  5. It reads standard input when given no file operands.

  6. One bad operand does not stop the others, and the exit code reflects the failure.

  7. It checks the result of the final flush and reports write errors.

  8. It keeps the default SIGPIPE behaviour unless it handles EPIPE everywhere.

  9. It does not hard-code paths, colours or locale, and honours TMPDIR and NO_COLOR where relevant.

  10. It has a test script that checks output and exit codes, and builds clean with -Wall -Wextra and the sanitizers.

  11. It ships a manual page and installs with DESTDIR support.

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.