|
|
As indicated in ``Compiling and linking'', information or control data can be passed to a C program as an argument on the command line. When you execute the program, command line arguments are made available to the function main() in two parameters, an argument count, conventionally called argc, and an argument vector, conventionally called argv. argc is the number of arguments with which the program was invoked. argv is an array of pointers to characters strings that contain the arguments, one per string. Because the command name itself is considered to be the first argument, or argv[0], the count is always at least.
If you plan to accept run-time parameters in your program, you need to include code to deal with the information. ``Using argv[1] to pass a filename'' and ``Using command line arguments to set flags'' show program fragments that illustrate two common uses of run-time parameters:
causes prog to attempt to open the specified file.
causes prog to set the corresponding variables for each of the options specified. The getopt() function used in the example is the most common way to process arguments in UNIX operating system programs. See getopt(S) for more information.
Using argv[1] to pass a filename
#include <stdio.h>int main(int argc, char argv[]) { FILE fin; int ch;
switch (argc) { case 2: if ((fin = fopen(argv[1], "r")) == NULL) { / First string (%s) is program name (argv[0]). / / Second string (%s) is name of file that could / / not be opened (argv[1]). /
(void)fprintf(stderr, "%s: Cannot open input file %s\n", argv[0], argv[1]); return(2); } break; case 1: fin = stdin; break;
default: (void)fprintf(stderr, "Usage: %s [file]\n", argv[0]); return(2); }
while ((ch = getc(fin)) != EOF) (void)putchar(ch);
return (0);
}
Using command line arguments to set flags
#include <stdio.h> #include <stdlib.h>int main(int argc, char argv[]) { int oflag = 0; int pflag = 0; / Function flags / int rflag = 0; int ch;
while ((ch = getopt(argc, argv, "opr")) != -1) { / For options present, set flag to 1. / / If unknown options present, print error message. /
switch (ch) { case 'o': oflag = 1; break; case 'p': pflag = 1; break; case 'r': rflag = 1; break; default: (void)fprintf(stderr, "Usage: %s [-opr]\n", argv[0]); return(2); } } / Do other processing controlled by oflag, pflag, rflag. / return(0); }