getopt

Parses command line arguments and parameter lists.

Library:LibC
Classification:POSIX
Service:General C Services

Syntax

  #include <getopt.h> 
   
  int getopt (
     int            argc,
     char * const   argv[],
     const char    *optstr);
  

Parameters

argc

(IN) Specifies the number of arguments in the array.

argv

(IN) Specifies the argument array.

optstr

(IN) Points to option characters. If a character is followed by a colon, the option takes an argument.

Return Values

If successful, returns the next option character specified on the command line. Returns -1 when all options are parsed.

If an error occurs, returns

  • A colon if the function detects a missing argument and the first character of optstr was a colon.

  • A question mark if the function encounters an option character not in optstr or detects a missing argument and the first character of optstr was not a colon.

Remarks

On return from the getopt function, the following variables are set:

  • optarg—points to an option argument, if one exists.

  • optind—contains the index to the next argv argument for a subsequent call to getopt.

  • opterr—before the first call, initialized to 1.

  • optopt—saves the last known option character returned by getopt.

  • optreset—before the first call, initialized to 1.

You can set the optind to another value before a set of calls to getopt in order to skip over more or less argv entries.

To use getopt to evaluate multiple sets of arguments, or to evaluate a single set of arguments multiple times, you must set the variable optreset to 1 before the second and each additional set of calls to getopt, and the variable optind must be reinitialized.

See Also