GETOPT(3) UNIX Programmer's Manual GETOPT(3) NNAAMMEE getopt - get option letter from argv SSYYNNOOPPSSIISS iinntt ggeettoopptt((aarrggcc,, aarrggvv,, ooppttssttrriinngg)) iinntt aarrggcc;; cchhaarr ****aarrggvv;; cchhaarr **ooppttssttrriinngg;; eexxtteerrnn cchhaarr **ooppttaarrgg;; eexxtteerrnn iinntt ooppttiinndd;; eexxtteerrnn iinntt oopptteerrrr;; DDEESSCCRRIIPPTTIIOONN _G_e_t_o_p_t returns the next option letter in _a_r_g_v that matches a letter in _o_p_t_s_t_r_i_n_g. _O_p_t_s_t_r_i_n_g is a string of recognized option letters; if a letter is followed by a colon, the option is expected to have an argument that may or may not be separated from it by white space. _O_p_t_a_r_g is set to point to the start of the option argument on return from _g_e_t_o_p_t. _G_e_t_o_p_t places in _o_p_t_i_n_d the _a_r_g_v index of the next argument to be processed. Because _o_p_t_i_n_d is external, it is normally initialized to zero automatically before the first call to _g_e_t_o_p_t. When all options have been processed (i.e., up to the first non-option argument), _g_e_t_o_p_t returns EEOOFF. The special option ---- may be used to delimit the end of the options; EEOOFF will be returned, and ---- will be skipped. DDIIAAGGNNOOSSTTIICCSS _G_e_t_o_p_t prints an error message on _s_t_d_e_r_r and returns a ques- tion mark (??) when it encounters an option letter not included in _o_p_t_s_t_r_i_n_g. Setting _o_p_t_e_r_r to a zero will dis- able this error message. EEXXAAMMPPLLEE The following code fragment shows how one might process the arguments for a command that can take the mutually exclusive options aa and bb, and the options ff and oo, both of which require arguments: main(argc, argv) int argc; char **argv; { int c; extern int optind; extern char *optarg; . . Printed 7/9/88 July 9, 1988 1 GETOPT(3) UNIX Programmer's Manual GETOPT(3) . 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++) { . . . } . . . } HHIISSTTOORRYY Written by Henry Spencer, working from a Bell Labs manual page. Modified by Keith Bostic to behave more like the Sys- tem V version. BBUUGGSS ``-'' may be specified as an option letter, however it should never have an argument associated with it. This allows getopt to be used with programs that think that ``-'' means standard input. Printed 7/9/88 July 9, 1988 2 GETOPT(3) UNIX Programmer's Manual GETOPT(3) Option arguments are allowed to begin with ``-''; this is reasonable but reduces the amount of error checking possi- ble. _G_e_t_o_p_t 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 argu- ments, etc. Printed 7/9/88 July 9, 1988 3