getopt()

Parse options from a command line

Synopsis:

#include <unistd.h>

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

extern char * optarg;
extern int optind, opterr, optopt;

Arguments:

argc
The argument count that was passed to main().
argv
The argument array that was passed to main().
optstring
A string of recognized option letters; if a letter is followed by a colon, the option takes an argument. Valid option characters for optstring consist of a single alphanumeric character (i.e. a letter or digit).

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The getopt() function is a command-line parser that can be used by applications that follow the Utility Syntax Guidelines described below.

The optind global variable is the index of the next element of the argv[] vector to be processed. The system initializes optind to 1 when the program is loaded, and getopt() updates it when it finishes with each element of argv[]. Reset optind to 1 if you want to use getopt() to process additional argument sets.

The getopt() function returns the next option character from argv that matches a letter in optstring, if there's one that matches. If the option takes an argument, getopt() sets the global variable optarg to point to the option argument as follows:

  1. If the option is the last letter in the string pointed to by an element of argv, then optarg contains the next element of argv, and optind is incremented by 2.
  2. Otherwise, optarg points to the string following the option letter in that element of argv, and optind is incremented by 1.

The getopt() function returns -1 is returned and doesn't change optind if:

  • argv[optind] is NULL
  • *argv[optind] isn't the character '-'
  • argv[optind] points to the string "-".

This function returns -1 after incrementing optind, if:

  • argv[optind] points to the string "--".

If getopt() encounters an option character that isn't contained in optstring, it returns the ? character. If it detects a missing option argument, getopt() returns:

  • a colon (:) if the first character of optstring is a colon

    or:

  • a question mark (?) otherwise

and sets optopt to the option character that caused the error.

The getopt() always prints a diagnostic message to stderr unless opterr is set to 0, or the first character of optstring is a : character.

Utility Syntax Guidelines

The getopt() function may be used by applications that follow these guidelines:

  • When describing the syntax of a utility, the options are listed in alphabetical order. There's no implied relationship between the options based upon the order in which they appear, unless otherwise stated in the Options section, or:
    • the options are documented as mutually-exclusive and such an option is documented to override any incompatible options preceding it
    • when an option has option arguments repeated, the option and option argument combinations are interpreted in the order specified on the command line.

    If an option that doesn't have option arguments is repeated, the results depend on the application.

  • Names of parameters that require substitution by actual values may be shown with embedded underscores or as <parameter name>. Angle brackets are used for the symbolic grouping of a phrase representing a single parameter and portable applications shouldn't include them in data submitted to the utility.
  • Options may be documented individually, or grouped (if they don't take option arguments):
    utility_name [-a] [-b] [-c option_argument]
                 [-d|-e] [-foption_argument] [operand…]
             
    

    Or:

    utility_name [-ab] [-c option_argument]
                 [-d|-e] [-foption_argument] [operand…]
             
    

    Utilities with very complex arguments may be shown as:

    utility_name [options] [operand]
          
    
  • Unless specified, whenever an operand or option argument is, or contains, a numeric value:
    • the number is interpreted as a decimal integer
    • numerals in the range 0 to 2,147,483,647 are syntactically recognized as numeric values
    • when the utility description states that it accepts negative numbers as operands or option arguments, numerals in the range -2,147,483,647 to 2,147,483,647 are syntactically recognized as numeric values
    • ranges greater than those listed here are allowed.

    All numbers within the allowable range aren't necessarily semantically correct. A standard utility that accepts an option argument or operand that's to be interpreted as a number, and for which a range of values smaller than that shown above is permitted, describes that smaller range along with the description of the option argument or operand. If an error is generated, the utility's diagnostic message indicates that the value is out of the supported range, not that it's syntactically incorrect.

  • Arguments or option arguments enclosed in the "[" and "]" notation are optional and can be omitted. Portable applications shouldn't include the "[" and "]" symbols in data submitted to the utility.
  • Ellipses (…) are used to denote that one or more occurrences of an option or operand are allowed. When an option or an operand followed by ellipses is enclosed in brackets, zero or more options or operands may be specified. The forms:
    utility_name -f option_argument…[operand…]
    utility_name [-g option_argument]…[operand…]
             
    

    indicate that multiple occurrences of the option and its option argument preceding the ellipses are valid, with semantics as indicated in the Options section of the utility. In the first example, each option argument requires a preceding -f and at least one -f option_argument must be given.

  • When the synopsis is too long to be printed on a single line in the documentation, the indented lines following the initial line are continuation lines. An actual use of the command appears on a single logical line.

See also Guidelines 3,4,5,6,7,9 and 10 in the Base Definitions volume of the IEEE Std.1003.1-2001 Section 12.2, Utility Syntax Guidelines.

Returns:

One of the following:

  • the next option character specified on the command line
  • a colon if a missing argument is detected and the first character of optstring is a colon
  • a question mark if a missing argument is detected and the first character of optstring isn't a colon
  • a question mark if an option character is encountered that's not in optstring
  • -1 when all command-line options have been parsed

Examples:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main( int argc, char* argv[] )
  {
    int c, errflag = 0;

    while( ( c = getopt( argc, argv, "abt:" ) )
      != -1 ) {
      switch( c ) {
        case 'a': printf( "apples\n" );
                  break;
        case 'b': printf( "bananas\n" );
                  break;
        case 't': printf( "tree = %s\n", optarg );
                  break;
        case '?': ++errflag;
                  break;
      }
    }
    return EXIT_SUCCESS;
  }

Classification:

POSIX 1003.1

Safety:  
Cancellation point Read the Caveats
Interrupt handler No
Signal handler No
Thread No

Caveats:

A cancellation point may occur when a thread is executing getopt() if the opterr argument is nonzero.

Last modified: 2013-12-23

comments powered by Disqus