man page(1) manual page
Table of Contents

NAME

getopt, optarg, optind - get option letter from argument vector

SYNOPSIS

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

extern char *optarg;
extern int optind, opterr;

DESCRIPTION

getopt() returns the next option letter in argv that matches a letter in optstring. optstring must contain the option letters the command using getopt() will recognize; 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 is initialized to 1 before the first call to getopt.

When all options have been processed (that is, 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 will be returned, and ``--'' will be skipped.

DIAGNOSTICS

getopt() prints an error message on the 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 opterr to 0.

EXAMPLE

The following code fragment shows how one might 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))
        {
            .
            .
            .
        }
}

SEE ALSO

getopts(1)

WARNING

Changing the value of the variable optind, or calling getopt() with different values of argv, may lead to unexpected results.


Table of Contents