Getting Command-Line Arguments

Summary: Command-line arguments are passed to programs through argv, an array of pointers.

Arrays of pointers have one very common use—accessing command-line arguments. When a C program begins execution, DOS passes two arguments to it. The first argument, normally called argc, is an int variable that indicates the number of command-line arguments. The second, normally called argv, is a pointer to an array of strings. Each string in the array contains one of the command-line arguments.

Even if you don't plan to use argc and argv in your programs, you can expect to see them often in other C programs, so it's useful to know how they're used. The ARGV.C program uses argc and argv.

/* ARGV.C: Demonstrate accessing command-line arguments. */

#include <stdio.h>

void show_args( char *argument );

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

{

int count;

for( count=0; count < argc; count++ )

show_args( argv[count] );

return 0;

}

void show_args( char *argument )

{

printf( "%s\n", argument );

}

To make ARGV.C produce output, you must give it some command-line arguments. (If you run ARGV.C in the Graphical Development Environment, select Run/Debug from the Options menu and type the command-line arguments in the Program Arguments text box.) The program prints each argument on the screen.

If you use this command line, for instance,

argv harpo chico groucho zeppo

then ARGV.C gives this output:

C:\SOURCES\ARGV.EXE

harpo

chico

groucho

zeppo

The first argument may have surprised you. In DOS versions 3.0 and higher, the first string in the argv array (argv[0]) contains the drive specification and full pathname to the program that is executing. The drive and path you see will depend on how your system is configured. In the example the ARGV.EXE program is located in the SOURCES directory of drive C.

Thus, the value ofargcactually is one greater than the number of command-line arguments, and the first argument typed on the command line is the second string in the array (argv[1]). If you type the arguments shown above, the value of argc is 5 and argv[1] contains the argument harpo.