#include <unistd.h> int getopt(int argc, char * const argv[], const char *optionstring);
The getopt() function returns the next flag letter in the argv list that matches a letter in optionstring. The optarg external variable is set to point to the start of the flag's parameter on return from getopt()
getopt() places the argv index of the next argument to be processed in optind. The optind variable is external. It is initialized to 1 before the first call to getopt().
getopt() can be used to help a program interpret command line flags that are passed to it.
The special flag "--" (two hyphens) can be used to delimit the end of the options. When this flag is encountered, the "--" is skipped and EOF is returned. This flag is useful in delimiting arguments beginning with a hyphen that are not options.
None.
EOF | getopt() processed all flags (that is, up to the first argument that is not a flag). |
'?' | getopt() encountered a flag letter that was not included in optionstring. The variable optopt is set to the real option found in argv regardless of whether the flag is in optionstring of not. An error message is printed to stderr. The generation of error messages can be suppressed by setting opterr to 0. |
The getopt() function does not return an error.
See Code disclaimer information for information pertaining to code examples.
The following example processes the flags for a command that can take the mutually exclusive flags a and b, and the flags f and o, both of which require parameters.
#include <unistd.h> int main( 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 bflg++; break; case 'f': ifile = optarg; break; case 'o': ofile = optarg; break; case '?': errflg++; } /* case */ if (errflg) { fprintf(stderr, "usage: . . . "); exit(2); } } /* while */ for ( ; optind < argc; optind++) { if (access(argv[optind], R_OK)) { . . . } } /* for */ } /* main */
Top | UNIX-Type APIs | APIs by category |