/* * program to demonstrate how getopt works * it takes options -n, -t number, and s final name that isn't optional * * Matt Bishop, ECS 36A, Fall Quarter 2019 * * adapted from the manual */ #include #include #include #include #include /* * variables defined for getopt() */ extern char *optarg; /* argument to option */ extern int optopt; /* if error, bad option goes in here */ extern int optind; /* index of next argument */ /* * main routine */ int main(int argc, char *argv[]) { int nopt = 0; /* 1 if -n given */ int topt = 0; /* 1 if -t given */ int nsecs = 0; /* argument to -t */ /* * process options and their arguments, if any */ while((opt = getopt(argc, argv, "nt:")) != -1){ /* process any given argument */ switch(opt){ case 'n': /* -n: option with no argument */ nopt = 1; break; case 't': /* -t: option with argument */ topt = 1; /* check that the argument is a number */ nsecs = strtol(optarg, &eoptarg, 10); if (*optarg != '\0'){ * nope -- give up */ fprintf(stderr, "t option requires a number\n"); return(1); } break; case '?': /* unknown argument -- error */ default: fprintf(stderr, "Bad option \'%c\'\n", optopt); fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n", argv[0]); return(1); } } /* * print out the options and values on the command line * and the index of the next argument */ printf("nopt=%d; topt=%d; nsecs=%d; optind=%d\n", nopt, topt, nsecs, optind); /* * there should be 1 more argument to the command * check it */ if (optind >= argc){ fprintf(stderr, "Expected argument after options\n"); return(1); } /* * print the final argument */ printf("name argument = %s\n", argv[optind]); /* * bye! */ return(0); }