We can now explore command-line arguments with the following program:
#include <stdio.h>
int main(int argc, char *argv[] ) {
if( argc == 1 ){
printf( " No arguments given on command line.\n\n" );
printf( " usage: %s <argument1> <argument2> ... <argumentN>\n" ,
argv[0] );
return 0;
}
printf( "argument count = [%d]\n" , argc );
for( int i = 0 ; i < argc ; i++ ){
if( i == 0 )
printf( "executable = [%s]\n" , argv[i] );
else
printf( "argument %d = [%s]\n" , i , argv[i] );
}
}
This program first checks whether any arguments have been passed into main() via argv. If not, it prints a usage message and returns; otherwise, it iterates through argv, printing each argument on a line by itself.
Enter this program into a file called showArgs.c, save it, compile it, and run it with the following invocations:
showArgs
showArgs...