18
Chapter 2Writing Good GNU/Linux Software
2.1.1The Argument List
You run a program from a shell prompt by typing the name of the program.Optionally,you can supply additional information to the program by typing one or more words after the program name,separated by spaces.These are called
command-line arguments
.(You can also include an argument that contains a space,by enclosing theargument in quotes.) More generally,this is referred to as the program
’
s
argument list
because it need not originate from a shell command line.In Chapter 3,
“
Processes,
”
you
’
ll see another way of invoking a program,in which a program can specify theargument list of another program directly.When a program is invoked from the shell,the argument list contains the entirecommand line,including the name of the program and any command-line argumentsthat may have been provided.Suppose,for example,that you invoke the
ls
commandin your shell to display the contents of the root directory and corresponding file sizeswith this command line:
% ls -s /
The argument list that the
ls
program receives has three elements.The first one is thename of the program itself,as specified on the command line,namely
ls
.The secondand third elements of the argument list are the two command-line arguments,
-s
and
/
.The
main
functionof your program can access the argument list via the
argc
and
argv
parameters to
main
(if you don
’
t use them,you may simply omit them).The firstparameter,
argc
,is an integer that is set to the number of items in the argument list.The second parameter,
argv
,is an array of character pointers.The size of the array is
argc
,and the array elements point to the elements of the argument list,as NUL-terminated character strings.Using command-line arguments is as easy as examining the contents of
argc
and
argv
.If you
’
re not interested in the name of the program itself,don
’
t forgetto skip thefirst element.Listing 2.1 demonstrates how to use
argc
and
argv
.
Listing 2.1
(
arglist.c
) Using
argc
and
argv
#include <stdio.h>int main (int argc, char* argv[]){printf (“The name of this program is ‘%s’.\n”, argv[0]);printf (“This program was invoked with %d arguments.\n”, argc - 1);/* Were any command-line arguments specified? */if (argc > 1) {/* Yes, print them. */int i;printf (“The arguments are:\n”);for (i = 1; i < argc; ++i)