All rights reserved.
Redistribution and use in source and binary forms are permitted
provided that this notice is preserved and that due credit is given
to the University of California at Berkeley. The name of the University
may not be used to endorse or promote products derived from this
software without specific prior written permission. This software
is provided ``as is'' without express or implied warranty.
@(#)getopt.3 6.7 (Berkeley) 05/06/88
int argc;
char **argv;
char *optstring; extern char *optarg;
extern int optind;
extern int opterr;
Getopt places in optind the argv index of the next argument to be processed. Because optind is external, it is normally initialized to zero automatically before the first call to getopt .
When all options have been processed (i.e., up to the first non-option argument), getopt returns EOF . The special option -- may be used to delimit the end of the options; EOF will be returned, and -- will be skipped.
main(argc, argv) int argc; char **argv; { int c; extern int optind; extern char *optarg; . . . while ((c = getopt(argc, argv, "abf:o:")) != EOF) switch (c) { case `a': if (bflg) errflg++; else aflg++; break; case `b': if (aflg) errflg++; else bproc(); break; case `f': ifile = optarg; break; case `o': ofile = optarg; break; case `?': default: errflg++; break; } if (errflg) { fprintf(stderr, "Usage: ..."); exit(2); } for (; optind < argc; optind++) { . . . } . . . }
Option arguments are allowed to begin with ``-''; this is reasonable but reduces the amount of error checking possible.
Getopt is quite flexible but the obvious price must be paid: there is much it could do that it doesn't, like checking mutually exclusive options, checking type of option arguments, etc.