delorie.com/djgpp/doc/libc/libc_406.html | search |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
#include <unistd.h> int getopt(int argc, char * const *argv, const char *options); extern char *optarg; extern int optind, opterr, optopt; |
Parse options from the command line. options is a string of valid option characters. If a given option takes an argument, that character should be followed by a colon.
For each valid switch, this function sets optarg
to the argument
(if the switch takes one), sets optind
to the index in argv
that it is using, sets optopt
to the option letter found, and
returns the option letter found.
If an unexpected option is found, a question mark (`?') is returned.
If an option argument is missing, a colon (`:') is returned if the
first character in options is a colon, otherwise a question mark is
returned. In both cases, if opterr
is nonzero and the first character
in options is not a colon, an error message is printed to
stderr
.
The example below shows how `?' can still be used as an option (e.g., to request a summary of program usage) in addition to flagging an unexpected option and a missing argument.
The option character is returned when found. -1 is returned when there are no more options. A colon (`:') is returned when an option argument is missing and the first character in options is a colon. A question mark (`?') is returned when an invalid option is found or an option argument is missing and the first character in options is not a colon.
ANSI/ISO C | No |
POSIX | 1003.2-1992; 1003.1-2001 |
int c; opterr = 0; while ((c=getopt(argc, argv, ":?vbf:")) != -1) { switch (c) { case 'v': verbose_flag ++; break; case 'b': binary_flag ++; break; case 'f': output_filename = optarg; break; case ':': printf("Missing argument %c\n", optopt); usage(); exit(1); case '?': if (optopt == '?') { usage(); exit(0); } else { printf("Unknown option %c\n", optopt); usage(); exit(1); } } } |
[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
webmaster | delorie software privacy |
Copyright © 2004 | Updated Apr 2004 |