// // // // // // // // // // // // // // // // // // // // // // // // // // CS270 Class Example // // Author: Robert Heckendorn // University of Idaho // #include #include #include #include // this program reads in a command line // aflg gets set if there is a -a option // bflg gets set if there is a -b option // zflg gets set if there is a -z option // // a and b options are mutually exclusive // z prints out when it is discovered // o option takes a file name and prints out when it is discovered // extraneous words are considered files are printed out // // this program was "borrowed" and extensively modified from the Sun Solaris man // page for educational purposes only. // // compile: g++ ouroptTest.cpp // test: a.out ali -a bob -z -z carol -z -o don ella -o frida gill // // Robert Heckendorn Mar 6, 2006 // int main(int argc, char **argv) { // // // // // // // // // // // // // // begin of arg processing extern char *optarg; // if takes a value then it is returned here extern int optind; // index into argv extern int optopt; // invalid character on error extern int opterr; // set to zero to force getopt to be silent on errors // extern int optreset; int c; bool aflg, nflg, oflg, zflg, errflg; char *ofile; int num; aflg = nflg = oflg = zflg = errflg = false; ofile = NULL; num = 0; opterr = 0; // hunt for a string of options while ((c = getopt(argc, argv, "an:o:z")) != EOF) switch (c) { case 'a': // set flag aflg = true; break; case 'n': // take an integer argument char *endptr; int tmpnum; nflg = true; tmpnum = strtol(optarg, &endptr, 10); if (*endptr!='\0') { fprintf(stderr, "ERROR(%s): number on -n option: %s is not a legal integer.\n", argv[0], optarg); } else { num = tmpnum; } break; case 'o': // take a file (use once) if (oflg) { fprintf(stderr, "ERROR(%s): -o option can be used only once. First one is used.\n", argv[0]); } else { oflg = true; ofile = strdup(optarg); } break; case 'z': // set flag zflg = 1; break; case ':': // missing argument case fprintf(stderr, "ERROR(%s): option -%c requires an option\n", argv[0], optopt); errflg = 1; break; case '?': // bad option case default: fprintf(stderr, "ERROR(%s): option -%c is not an option\n", argv[0], optopt); errflg = 1; } // report any errors or usage request if (errflg) { fprintf(stderr, "usage: %s [-a] [-z] [-o ] files...\n", argv[0]); // do you want to continue? exit(2); } // pick off a nonoptions as if they were files for (; optind < argc; optind++) { (void)printf("file: %s\n", argv[optind]); } // end of arg processing // // // // // // // // // // // // // // what did we find? if (aflg) printf("option 'a' was found\n"); if (nflg) printf("option 'n' was found with number: %d\n", num); if (oflg) printf("option 'o' was found with file: %s\n", ofile); if (zflg) printf("option 'z' was found\n"); return 0; }