Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 135 ยท Standard Library

Command-Line Arguments

Learn how C programs read command-line arguments with argc and argv, convert them to numbers safely, parse options like -n 5 by hand, and test it all in the editor.

Most programs you run from a terminal take arguments: gcc -Wall main.c, ls -l /tmp, grep -i error log.txt. The words after the program name tell it what to do without asking questions interactively. In C, those words arrive as two parameters of main, traditionally called argc and argv.

This lesson shows exactly what argc and argv contain, how to turn arguments into numbers without trusting them, and how to parse options such as -v, -n 5 and --name=Ada by hand. Our online editor runs programs without arguments, so you'll also learn a simple trick to simulate a command line, which is a handy testing technique in real projects too.

argc and argv

When main takes two parameters, the C runtime fills them in before your code starts:

C
int main(int argc, char *argv[])
  • argc (argument count) is the number of strings in argv. It's never negative and is normally at least 1.
  • argv (argument vector) is an array of pointers to null-terminated strings. argv[0] is the program's name (or the path used to start it), argv[1] is the first real argument, and so on.
  • The standard guarantees argv[argc] is a null pointer, so you can also loop until you reach NULL.

You'll often see char **argv instead of char *argv[]. In a parameter list they mean the same thing, because an array parameter is really a pointer (see Pointers to Pointers). The names argc and argv are only a convention; the types are what matter.

Run this program. In our editor nobody types arguments, so it prints just one entry:

C What argc and argv contain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

argc is 1 and argv[0] holds a path such as ./binary, which is the name our server gave the compiled program. If you compiled this on your own machine and ran ./show one "two words" 3, you'd see:

TEXT
argc = 4
argv[0] = "./show"
argv[1] = "one"
argv[2] = "two words"
argv[3] = "3"

Notice three things. Every argument is a string, even 3. The shell, not C, splits the command line into words, so the quotes around two words keep it together and are removed before your program sees it. And on Unix-like systems the shell also expands wildcards: ./show *.c delivers each matching file name as a separate argument, while Windows passes *.c through and leaves expansion to the program.

Note: argv[0] can be anything the launching program chose, including an empty string, and on some embedded systems argc is even 0. Use it for messages ("usage: ./show ..."), never for security decisions or to find files next to the program.

Simulating arguments in the editor

Since you can't type a command line here, move the real work into a function with the same signature as main and call it with a fake argument list. This pattern also makes the logic easy to unit-test later:

C A fake command line for testing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The fake array ends with NULL just like the real one, and fake_argc is computed from the array size so you can't get it wrong when you add or remove names. Try deleting "Ada", "Linus", "Grace",: the program prints a usage message to stderr and returns 1. (String literals are read-only, so run must never modify argv[i] here; real argv strings may be modified, but it's rarely a good idea.)

The rest of this lesson uses the same pattern. In your own programs you'd simply write return run(argc, argv);.

Converting arguments to numbers

Arguments are text, so ./repeat 3 gives you the string "3", not the number 3. atoi looks tempting, but it returns 0 for garbage and has undefined behavior on overflow, so you can't tell "0" from "oops". Use strtol and check three things: that some digits were read, that nothing is left over, and that the value fits (Converting Strings and Numbers covers this in depth).

C Summing numeric arguments safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints sum = 13 (10 โˆ’ 4 + 7) and reports three bad arguments: 12abc has trailing junk, the empty string has no digits, and 99999999999 is too big for an int. Because some input was bad, it returns EXIT_FAILURE, so a shell script calling it can notice. For floating-point arguments, use strtod the same way.

Parsing options by hand

Command-line tools follow a few common conventions, mostly inherited from Unix:

Form Example Meaning
Short flag -v Turn something on
Combined short flags -vq Same as -v -q
Short option with value -n 5 or -n5 The value follows
Long flag --verbose Readable name for a flag
Long option with value --name=Ada or --name Ada Value after = or in the next argument
End of options -- Everything after it is a plain argument, even -x
Operands file.txt Anything that isn't an option

Here is a small tool, shout, that prints its operands in upper case. It understands -n COUNT (repeat count), -v (verbose), --prefix=TEXT and --. Read how each argument is classified:

C A hand-written option parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

It prints count=2 prefix='> ' words=2, then > HELLO twice and > -WORLD twice. Without the --, -world would be rejected as an unknown option; that's precisely why the convention exists (think of deleting a file literally named -world). A lone - is treated as an operand, because by tradition it means "standard input".

Experiment with the fake array: remove the "2" after -n to see the "needs a value" error, or add "-x" to trigger the usage message. Exit status 2 is the usual choice for "you used the command wrong", distinct from 1 for "the work failed".

A few design rules make tools pleasant to use:

  • Print errors and usage text to stderr, so they don't end up in a file when the user redirects output with >.
  • Support -h/--help that prints usage to stdout and exits with 0.
  • Return EXIT_SUCCESS (0) on success and a nonzero status on failure (see Useful stdlib.h Functions).
  • Don't copy argument strings you only read; pointers into argv stay valid for the whole program.

getopt: the POSIX helper

Writing parsers by hand gets tedious, and edge cases (combined flags like -vn5) are easy to miss. On Linux, macOS and other POSIX systems, <unistd.h> provides getopt, which handles short options for you. It is not part of standard C, so it isn't available with MSVC on Windows (use a small portable library there, or your own parser).

C
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>     /* POSIX, not ISO C */

int main(int argc, char *argv[])
{
    int count = 1;
    int verbose = 0;
    int ch;

    /* "vn:" = -v is a flag, -n takes a value (the colon) */
    while ((ch = getopt(argc, argv, "vn:")) != -1) {
        switch (ch) {
        case 'v':
            verbose = 1;
            break;
        case 'n':
            count = atoi(optarg);   /* optarg points at the value */
            break;
        default:                    /* '?' for unknown option or missing value */
            fprintf(stderr, "usage: %s [-v] [-n COUNT] WORD...\n", argv[0]);
            return 2;
        }
    }

    /* optind is the index of the first operand */
    for (int i = optind; i < argc; i++) {
        for (int k = 0; k < count; k++) {
            printf("%s%s\n", verbose ? "* " : "", argv[i]);
        }
    }
    return 0;
}

getopt accepts -v -n 3, -vn3 and -n3 -v alike, prints its own error message for unknown options, and stops at --. GNU systems add getopt_long in <getopt.h> for --long-options. For anything beyond a handful of options, they save time and match what users expect.

Environment variables: the other input channel

Arguments aren't the only thing a program receives from the outside. Every process also inherits environment variables such as HOME, PATH or LANG. Read them with getenv from <stdlib.h>, which returns NULL if the variable isn't set:

C Arguments plus an environment default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The order "argument, then environment variable, then default" is a common and friendly convention. Many systems also pass a third, non-standard parameter to main (char *envp[]); prefer getenv, which is portable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program is started as ./app -n 10 "a b". What is argc?

    argv holds ./app, -n, 10 and a b. The quotes keep a b as one argument, so argc is 4.
  2. 2. What is the type of argv[1] when it holds 10?

    Every argument is a string. You must convert it yourself, for example with strtol.
  3. 3. Why is strtol better than atoi for numeric arguments?

    atoi returns 0 for invalid input and has undefined behavior on overflow. With strtol you can check the end pointer and errno.
  4. 4. What does the argument -- usually mean to a command-line tool?

    After --, arguments that start with - are treated as operands, which lets users pass names such as -world.
  5. 5. What is guaranteed about argv[argc]?

    The C standard requires argv[argc] to be a null pointer, so loops can stop at NULL instead of using argc.

Summary

  • int main(int argc, char *argv[]) receives the argument count and an array of strings; argv[0] is the program name and argv[argc] is NULL.
  • The shell splits words, removes quotes and (on Unix) expands wildcards before your program starts.
  • Every argument is text: convert numbers with strtol/strtod and check the end pointer, errno and the range.
  • Parse options in a loop that stops at the first operand or at --; send errors and usage text to stderr and return a nonzero status.
  • POSIX getopt (and GNU getopt_long) handle option parsing on Unix-like systems but aren't standard C.
  • To test argument handling without a terminal, move the logic into a run(argc, argv) function and call it with a fake, NULL-terminated array.

Next: Linked Lists, where you'll build your first dynamic data structure out of structs and pointers.