GETOPT(3C) — Kubota Pacfic Computer Inc. (C Programming Language Utilities)
NAME
getopt − get option letter from argument vector
SYNOPSIS
int getopt (argc, argv, optstring)
int argc;
char ∗∗argv, ∗opstring;
extern char ∗optarg;
extern int optind, opterr;
DESCRIPTION
getopt returns the next option letter in argv that matches a letter in optstring. It supports all the rules of the command syntax standard (see intro(1)). New commands will adhere to the command syntax standard, if they use getopts(1) or getopt to parse positional parameters and check for options that are legal for that command.
optstring must contain the option letters expected to be recognized by the command using getopt; 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 initialized to 1 before the first call to getopt.
When all options have been processed (i.e., 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, and “−−” skipped.
DIAGNOSTICS
getopt prints an error message on standard error and returns a question mark (?) when it encounters an option letter not included in optstring or no option-argument after an option that expects one. This error message may be disabled by setting to 0.
EXAMPLE
The following code fragment shows how to process the arguments for a command that can take the mutually exclusive options a and b, and the option o, which requires an option-argument:
main (argc, argv)
int argc;
char ∗∗argv;
{
int c;
extern char ∗optarg;
extern int optind;
.
.
.
while ((c = getopt(argc, argv, "abo:")) != -1)
switch (c) {
case ′a′:
if (bflg)
errflg++;
else
aflg++;
break;
case ′b′:
if (aflg)
errflg++;
else
bproc( );
break;
case ′o′:
ofile = optarg;
break;
case ′?′:
errflg++;
}
if (errflg) {
(void)fprintf(stderr, "usage: . . . ");
exit (2);
}
for ( ; optind < argc; optind++) {
if (access(argv[optind], 4)) {
.
.
.
}
WARNING
Although the following command syntax rule (see intro(1)) relaxations are permitted under the current implementation, they should not be used because they may not be supported in future releases of the system. As in the EXAMPLE section above, a and b are options, and the option o requires an option-argument:
cmd −aboxxx file (Rule 5 violation: options with option-arguments
must not be grouped with other options)
cmd −ab −oxxx file (Rule 6 violation: there must be white space
after an option that takes an option-argument)
SEE ALSO
Changing the value of the variable optind, or calling getopt with different values of argv, may lead to unexpected results.
September 02, 1992