ZetCode

Command-line arguments in K&R C

last modified December 5, 2026 K&R C 1978

A UNIX command takes its file names and options from the command line: wc -l poem.txt. The shell splits the line into words and passes them to the program, and C hands them to main as an array of strings. This article shows how a program reads them, parses options the way the UNIX tools do, and reports success or failure through its exit status.

argc and argv

main is called with two arguments. The first, by convention called argc, is the number of words on the command line. The second, argv, is a pointer to an array of character pointers, one for each word.

args.c
#include <stdio.h>

int main(argc, argv)
int argc;
char *argv[];
{
    int i;

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

argv[0] is the name by which the program was called, so argc is at least 1. The quotes of the shell make two words a single argument, and the shell removes them; the program never sees them. argv[argc] is a null pointer. On V7 the program is a.out, and that is its argv[0].

$ gcc -std=c89 -pedantic -Wall -Wextra -o args args.c
$ ./args one 'two words' 3
argc = 4
argv[0] = "./args"
argv[1] = "one"
argv[2] = "two words"
argv[3] = "3"

Walking the arguments

argv is a pointer to the first element of an array of pointers, so it can be declared char **argv and stepped through the array like any other pointer, as the pointers and arrays article shows.

echoargs.c
#include <stdio.h>

/* print the arguments on one line, like echo */
int main(argc, argv)
int argc;
char **argv;
{
    while (--argc > 0)
        printf("%s%s", *++argv, argc > 1 ? " " : "");
    printf("\n");
    return 0;
}

This is a small echo command. --argc counts the arguments that remain, and *++argv moves to the next argument before using it, which skips the program name. A blank goes after every argument but the last. The shell has already split the line at the blanks, so the extra blanks of the command line are gone.

$ gcc -std=c89 -pedantic -Wall -Wextra -o echoargs echoargs.c
$ ./echoargs Hello   there from    the command line
Hello there from the command line

Numbers and the exit status

The arguments are strings. A program that expects numbers converts them, for example with atol. A program called with the wrong arguments prints a usage message and returns a non-zero exit status.

addargs.c
#include <stdio.h>
#include <stdlib.h>

int main(argc, argv)
int argc;
char *argv[];
{
    int i;
    long sum;

    if (argc < 2) {
        fprintf(stderr, "usage: %s number ...\n", argv[0]);
        return 1;
    }
    sum = 0;
    for (i = 1; i < argc; i++)
        sum += atol(argv[i]);
    printf("%ld\n", sum);
    return 0;
}

The value that main returns, or passes to exit, becomes the exit status of the program, which the shell keeps in $?. By convention 0 means success. The usage message names the program with argv[0], so it is right under any name the program is called by.

$ gcc -std=c89 -pedantic -Wall -Wextra -o addargs addargs.c
$ ./addargs 100000 -42 7
99965
$ ./addargs
usage: ./addargs number ...
$ echo $?
1

Options

UNIX commands take options that begin with a minus sign and come before the other arguments. Several one-letter options may share one minus sign: -lw means -l -w. The next program counts lines, words, and characters of its input, and the options choose which counts it prints.

count.c
#include <stdio.h>

#define IN  1
#define OUT 0

int main(argc, argv)
int argc;
char *argv[];
{
    int c, lflag, wflag, cflag, state;
    long lines, words, chars;

    lflag = wflag = cflag = 0;
    while (--argc > 0 && (*++argv)[0] == '-')
        while ((c = *++argv[0]) != '\0')
            switch (c) {
            case 'l': lflag = 1; break;
            case 'w': wflag = 1; break;
            case 'c': cflag = 1; break;
            default:
                fprintf(stderr, "count: illegal option -%c\n", c);
                return 2;
            }
    if (argc > 0) {
        fprintf(stderr, "usage: count [-lwc]\n");
        return 2;
    }
    if (!lflag && !wflag && !cflag)
        lflag = wflag = cflag = 1;

    lines = words = chars = 0;
    state = OUT;
    while ((c = getchar()) != EOF) {
        chars++;
        if (c == '\n')
            lines++;
        if (c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if (state == OUT) {
            state = IN;
            words++;
        }
    }
    if (lflag)
        printf(" lines %ld", lines);
    if (wflag)
        printf(" words %ld", words);
    if (cflag)
        printf(" chars %ld", chars);
    printf("\n");
    return 0;
}

The outer loop moves to each argument that begins with a minus sign. (*++argv)[0] is the first character of the next argument; the parentheses are needed, because [] binds tighter than * and ++. The inner loop steps through the letters of the option with *++argv[0], which increments the pointer argv[0] itself. An unknown letter ends the program with status 2. Without options, the program prints all three counts.

$ gcc -std=c89 -pedantic -Wall -Wextra -o count count.c
$ ./count < poem.txt
 lines 9 words 56 chars 274
$ ./count -l < poem.txt
 lines 9
$ ./count -wc < poem.txt
 words 56 chars 274
$ ./count -l -c < poem.txt
 lines 9 chars 274
$ ./count -x < poem.txt
count: illegal option -x
$ echo $?
2

Option values and file names

An option may take a value, written in the same word or in the next one: -n3 or -n 3. The arguments after the options are often file names; a program without file names reads its standard input, so it can work in a pipeline. The next program prints the first lines of each file. The second file of the example is this one:

short.txt
one
two
three

The program counts the newlines it copies and stops after the requested number of lines.

firstn.c
#include <stdio.h>
#include <stdlib.h>

/* copy the first n lines of fp to the standard output */
int first(fp, n)
FILE *fp;
int n;
{
    int c;

    while (n > 0 && (c = getc(fp)) != EOF) {
        putchar(c);
        if (c == '\n')
            n--;
    }
    return 0;
}

int main(argc, argv)
int argc;
char *argv[];
{
    FILE *fp;
    char *prog;
    int n, status;

    prog = argv[0];
    n = 5;
    if (argc > 1 && argv[1][0] == '-' && argv[1][1] == 'n') {
        if (argv[1][2] != '\0')         /* -n3 */
            n = atoi(&argv[1][2]);
        else if (argc > 2) {            /* -n 3 */
            n = atoi(argv[2]);
            argc--;
            argv++;
        }
        argc--;
        argv++;
    }
    if (argc == 1) {
        first(stdin, n);
        return 0;
    }
    status = 0;
    while (--argc > 0) {
        if ((fp = fopen(*++argv, "r")) == NULL) {
            fprintf(stderr, "%s: cannot open %s\n", prog, *argv);
            status = 1;
            continue;
        }
        printf("== %s\n", *argv);
        first(fp, n);
        fclose(fp);
    }
    return status;
}

The option is checked character by character. The value starts at &argv[1][2], the third character of the word, or it is the next word, which the program then skips as well. A file that cannot be opened is reported, and the program goes on with the others; the status 1 at the end tells the caller that something went wrong. The default is five lines.

$ gcc -std=c89 -pedantic -Wall -Wextra -o firstn firstn.c
$ ./firstn -n2 poem.txt missing.txt short.txt
== poem.txt
The tide comes in without a sound,
it fills the harbour stone by stone,
./firstn: cannot open missing.txt
== short.txt
one
two
$ echo $?
1
$ ./firstn -n 1 poem.txt
== poem.txt
The tide comes in without a sound,
$ ./firstn < short.txt
one
two
three

The environment

Besides its arguments, a program receives the environment: a list of strings of the form name=value that the shell passes to every command it starts. UNIX passes it to main as a third argument, an array of string pointers ended by a null pointer, and getenv looks up a single name. The environment came with V7 UNIX, a year after the book, whose main has only two parameters.

environ.c
#include <stdio.h>
#include <stdlib.h>

int main(argc, argv, envp)
int argc;
char *argv[], *envp[];
{
    int i;
    char *s;

    for (i = 0; envp[i] != NULL; i++)
        printf("envp[%d] = %s\n", i, envp[i]);
    printf("%s has %d arguments and %d variables\n", argv[0], argc - 1, i);

    s = getenv("GREETING");
    printf("GREETING: %s\n", s != NULL ? s : "(not set)");
    s = getenv("COLOUR");
    printf("COLOUR: %s\n", s != NULL ? s : "(not set)");
    return 0;
}

The program prints the environment and looks up two names. A Linux environment has dozens of variables, so the example starts the program with env -i, which empties the environment, and sets one variable for it. getenv returns a null pointer for a name that is not set.

$ gcc -std=c89 -pedantic -Wall -Wextra -o environ environ.c
$ env -i GREETING='Hello there' ./environ
envp[0] = GREETING=Hello there
./environ has 0 arguments and 1 variables
GREETING: Hello there
COLOUR: (not set)

V7 has no env command. The Bourne shell passes a variable set in front of the command along with the rest of the environment, which on V7 has only the home directory and the search path of the user.

$ cc environ.c
$ GREETING='Hello there' a.out
envp[0] = GREETING=Hello there
envp[1] = HOME=/usr/dmr
envp[2] = PATH=:/bin:/usr/bin
a.out has 0 arguments and 3 variables
GREETING: Hello there
COLOUR: (not set)

Source

Dennis Ritchie: C Reference Manual (1975)

Linux manual: getenv

In this article we have read the command line in K&R C: argc and argv, stepping through the arguments with a pointer, converting numbers, the exit status, options in the style of the UNIX tools, option values and file names, and the environment. This completes the input and output part of the series; the next part writes the classic programs, starting with the reverse Polish calculator.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.