Error Handling and the Command Line

Article · 3:00

argc and argv, errno, perror and strerror - reporting failure in a language with no exceptions.

C has no exceptions. A function reports failure in its return value, and the caller checks it - every time. The conventions are not uniform, which is itself worth knowing: malloc returns NULL, fopen returns NULL, most system calls return -1, and main returns 0 for success and non-zero for failure.

When a library or system call fails it also sets errno, a global holding a code for what went wrong. Three rules make it usable. Only inspect it after a call has already indicated failure - a successful call may leave it at any value. Set it to zero first when the function you are calling can return a legitimate -1, such as strtol. And read it immediately, because the next library call may overwrite it.

perror("context") prints your message, a colon, and the text for the current errno to standard error. strerror(errno) returns that text as a string when you want to format it yourself.

Command-line arguments arrive as argc, the count, and argv, an array of strings. argv[0] is the program's own name, so real arguments start at argv[1], and argv[argc] is NULL. Check argc before indexing - reading argv[1] when nothing was passed is undefined behaviour.

Send errors to stderr rather than stdout. They are different streams precisely so the output of a program can be piped somewhere while its complaints still reach the terminal.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    /* argv[0] is the program name, so real arguments start at 1.
       Check argc BEFORE indexing. */
    if (argc < 2) {
        fprintf(stderr, "usage: %s <file> [count]\n", argv[0]);
        return EXIT_FAILURE;
    }

    FILE *f = fopen(argv[1], "r");
    if (!f) {
        /* errno was set by the failed call. Read it immediately - the
           next library call may overwrite it. */
        perror(argv[1]);                              /* file: No such file... */
        fprintf(stderr, "detail: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

    long count = 10;
    if (argc >= 3) {
        /* strtol can legitimately return 0 or LONG_MAX, so errno has to
           be cleared first to tell a real value from an error. */
        errno = 0;
        char *end;
        count = strtol(argv[2], &end, 10);

        if (end == argv[2] || *end != '\0') {
            fprintf(stderr, "'%s' is not a number\n", argv[2]);
            fclose(f);
            return EXIT_FAILURE;
        }
        if (errno == ERANGE) {
            fprintf(stderr, "'%s' is out of range\n", argv[2]);
            fclose(f);
            return EXIT_FAILURE;
        }
    }

    printf("reading %ld lines from %s\n", count, argv[1]);
    fclose(f);
    return EXIT_SUCCESS;     /* 0. Anything else means failure. */
}

/* Errors go to stderr, not stdout - the streams are separate so that
   ./program > out.txt still shows you the complaints. */