/* Example of using getopt to parse command line arguments. This code uses the getopt() function, there is a richer library (gnu getopt_long) as well. getopt supports finding command line options that begin with the character "-" (as in "ls -al"). Some options are simply either present or not, others can indicate some value. For example, a program that allows the user to specify two numbers to add could have a command line like this: prog -x 100 -y 200 The progam below doesn't do anything other than print out some values that can be set from the command line. It supports four different options: -v : a toggle (sets the variable "verbose" to 1). -n num: sets the value of a variable named d -x num: sets the value of a variable named foo (just using x for this to make sure you realize there is no automatic connection between the option character and what you do with the following value). -i filename: sets the value of a C string (char *) variable The program below insists that you enter something for the -i option, the others all have default values... Some possible ways to test this program out: > getoptexample -v -n 100 -i hello > getoptexample -i somefile > getoptexample -x 100 -n 200 -i blah */ #include #include #include int main(int argc, char **argv) { char c; int verbose=0; int n=0; int foo=0; char *filename = NULL; while ((c=getopt(argc,argv,"vn:x:i:"))>=0) { switch(c) { case 'v': verbose=1; break; case 'n': n = atoi(optarg); break; case 'x': foo = atoi(optarg); break; case 'i': filename = optarg; break; case '?': /* invalid option - getopt returns a '?' */ exit(1); } } if (filename==NULL) { fprintf(stderr,"input file name must be specified!\n"); exit(1); } printf("verbose is %s\n",(verbose?"on":"off")); printf("n is %d\n",n); printf("foo is %d\n",foo); printf("Filename is : %s\n",filename); return(0); }