13.4 Command-Line Arguments
The C language provides a mechanism for a program to obtain input parameters from the envi-ronment in which it executes. These are termed “command-line arguments” and are passed to the program when it begins execution. Until now we have specified the interface of main() as
int main(void)
which is one of the two interfaces permitted by the ISO C standard. The other consists of two arguments
int main(int argc, char *argv[])
where argc stands for argument count and argv stands for argument vector.
Style Note. The two parameters, of course, do not have to be named argc and argv, but this is a long-standing convention and should be upheld to assist code readability.
The value of argc is the number of command-line parameters passed to the program upon execution. The parameter argv is a pointer to an array of character strings, where each string is one of the passed command-line parameters. The length of this array is argc+1 and the end element, argv[argc] is NULL. The value of argc is always at least one, as argv[0] is the name by which the program was invoked. If argc equals one, then there are no command-line arguments after the program name.
Consider the example program below. This program simply takes the set of command-line strings referred to by argv and prints them to stdout. We will assume the program executable is named “echo”.
1 #include <stdio.h>
2
3 /* Print command-line arguments to stdout. */ 4 int main (int argc, char *argv[ ])
5 {
6 int i;
7 for (i = 1; i < argc; ++i)
8 printf("%s ", argv[i]);
9 printf("\n");
10 }
When a program is invoked from a command-line, each white-space separated string of characters including the program name becomes a command-line argument. Thus, typing
echo one two three 123
stores the strings "echo", "one", "two", "three" and "123" in locations referred to by argv[0] to argv[4], respectively, and argc is equal to five. This program then prints all arguments except argv[0]. Note, redirection commands do not appear as command-line arguments, so
echo one >outfile.txt two three 123
will print
one two three 123
in the file named outfile.txt.
No comments:
Post a Comment