|
|
# include <unistd.h>int getopt (argc, argv, optstring) int argc; char * const argv[]; const char *optstring;
extern char *optarg; extern int optind, opterr, optopt;
optstring must contain the option letters the command using getopt recognizes; if a letter is followed by a colon, the option is expected to have an argument, or group of arguments, which must be separated from it by white space.
optarg is set to point to the start of the option-argument on return from getopt.
getopt places in optind the argv index of the next argument to be processed. optind is external and is initialized to 1 before the first call to getopt. Each time getopt( ) parses an option, it increments optind by one with only one exception: if the option is the last letter in the string argv[optind] and the option also takes an argument, optind is incremented by two.
The following rules comprise the standard for command line syntax:
The routine getopt is the command line parser that enforces the rules of this command syntax standard.
getopt returns the next valid option letter entered on the command line.
When all options have been processed (that is, up to the first non-option argument), getopt returns -1. The special option ``--'' may be used to delimit the end of the options; when it is encountered, -1 is returned, ``--'' is skipped, and optind is incremented by one.
If argv[optind] is NULL or points to a string "-", or if *argv[optind] is not the character `-', getopt(S-osr5) returns -1 without changing optind.
In both error conditions, a question mark (?) is returned and optopt is set to the value of the option character causing the error. A colon character (:) is returned instead if optstring starts with a colon and an option-argument is missing.
Changing the value of the variable optind or calling
getopt with different values of argv
may lead to unexpected results.
#include <unistd.h> main (argc, argv) int argc; char **argv; { int c; int aflg, bflg, errflg; char *ofile; extern char *optarg; extern int optind, optopt; . . . while ((c = getopt(argc, argv, "abo:")) != -1) switch (c) { case 'a': if (bflg) errflg++; else aflg++; break; case 'b': if (aflg) errflg++; else bflg++; bproc( ); break; case 'o': ofile = optarg; break; case ':': /* argument for -o is missing */ errflg++; fprintf(stderr, "option -%c requires an argument\n", optopt); case '?': errflg++; fprintf(stderr, "option -%c not recognized\n", optopt); } if (errflg) { (void)fprintf(stderr, "usage: . . . "); exit (1); } for ( ; optind < argc; optind++) { if (access(argv[optind], R_OK)) { . . . }
Intel386 Binary Compatibility Specification, Edition 2 (iBCSe2)
;
X/Open CAE Specification, System Interfaces and Headers,
Issue 4, 1992.
.