Command-Line Arguments

One of the reasons for C's success in building software tools is the ease with which you can access command-line arguments. All tokens on the command line (even the program name) are arguments to main. The following program prints each command-line argument on a line by itself.

/* ecko: print command-line arguments */

#include <stdio.h>
main(int argc, char * argv[])
int i;
for(i=0; i<argc; ++i)
   puts (argv [i] );
return 0;
If the command line is

C> ecko one two three

then the output is

The first argument (argc) is the number of arguments entered (4 in this case). The second argument (argv) is an array of pointers to character as shown in Figure 2.

The first argument (argv[O]) is always the full path name of the program's executable file (except on versions of MS-DOS prior to 3.0, where it is an empty string).


Most operating systems allow you to use wildcard characters on the command line (e.g., * matches 0 or more characters, ? matches 0 or 1 in MS-DOS). These are usually associated with filenames. For example, the command

C> ecko *.c

should print the names of all .c files in the current directory, one-per-line.

Not all operating environments do wildcard processing by default, however (UNIX does, MS-DOS and VAX/VMS do not). To activate it using Borland C under MS-DOS, you will need to link with the file \BORLANDC\LIB\WILDARGS.OBJ:

C> bcc ecko. c \borlandc\lib\wildargs.obj

The file for Microsoft C is \C700\LIB\SETARGV. OBJ.

Command-Line Options

Many programs accept options (sometimes called switches) on the command line to alter execution. You specify options by a special prefix character, usually a dash or a forward slash. For example, Microsoft C accepts, as two among many, the options -c (do not link), and -Od (turn off optimization):

C> cl -c -Od ecko.c

These options must precede the filenames to be processed. Listing 9, a sample program for printing a directory listing, shows how to process options before other arguments. Valid options are:

The output of the command

C> list -lr *.c *.h

Dir: *.c (Order = -1, Full = 1)
Dir: *.h (Order = -1, Full = 1)
This technique allows you to combine options in the same argument (as shown above), or to separate them (-l -r). The code that actually reads the directory (function dir) would likely be non-portable, since file systems are highly platform-dependent.

With another technique you can intersperse options among the other arguments, so that each file is processed with its own set of options. The file printer program in Listing 10 can process a command such as

C> pr -n -c10 file1.c -nc1qL file2.c file3.c
This command prints 10 copies of file1.c with line numbers on the default printer, and prints one copy of the other files without line numbers formatted for a laser printer (the flag n is a toggle). The options are: