The getopt(3) Function

What helps to make UNIX commands consistent in their syntax is that most commands use the library function getopt(3). Its synopsis is as follows:

#include <unistd.h>

extern char *optarg;
extern int optind;    /* initialized to 1 */
extern int optopt;
extern int opterr;    /* initialized to 1 */
extern int optreset;  /* extension to IEEE Std1003.2 "POSIX.2" */

int getopt(int argc, char * const *argv, const char *optstring);

extern void getoptreset(void);            /* SGI IRIX 6.5 only */

The getopt(3) function returns the option letter that is parsed. Alternatively, -1 is returned when the end of the options has been reached. The value ? is returned when an unrecognized option character has been encountered. If the argument optstring

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.