Skip to main content
Engineering LibreTexts

14.1: Command Line Arguments

  • Page ID
    35866
  • Question: How do various utilities “read” the arguments that you place after them on the command line? For example, you might have a utility that archives (compresses) a file, creating a new (compressed) file. You might use it like this from a DOS or shell prompt:

    C:>archive foo.txt foo.arc
    

    The program is called archive (archive.exe), and you're telling it to compress the file foo.txt and create a new file called foo.arc. This is much faster than using scanf() type input from within the program (i.e., having the user run the program, at which point the program then prompts for the two file names). C allows a very simple method of obtaining these command line arguments. This requires a modification to the declaration of main():

    void main( int argc, char *argv[] )
    

    The first parameter is called the argument count and tells you how many items (strings) where entered on the command line. In the example above, argc would be 3. The second parameter is called the argument vector. It is an array of pointers to strings. These strings are the items entered on the command line. Thus argv[0] points to "archive", argv[l] points to "foo.txt", and argv[2] points to “foo.arc".

    If argc is 1, then no arguments were added after the executable name. Below is a simple echo example. This will echo whatever was typed in on the command line.

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

    Note that since argv is an array of pointers, then argv[x] is also a pointer, and is treated just like any other pointer to characters. Thus, you can use functions like strcpy() or strcmp() on it. For numeric arguments (such as "archive blah 23"), you may convert the ASCII string ("23") into either an integer, long integer, or float via the atoi(), atol(), and atof() functions, respectively.

    Other possibilities include printing out directions if argc is 1 or if the only added argument is “?”. It is possible to take this further by adding “switches” or “flags” to the argument list so that arguments can be presented in any order. This is precisely what is done if the compiler or linker is run directly rather than via the IDE.

    In summation, command line arguments are a very handy and quick way of getting values into a program. As an exercise, alter one of your previous programs to utilize command line arguments rather than the scanf() approach.