getopt()--Get Flag Letters from Argument Vector


  Syntax
 #include <unistd.h>

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


  Service Program Name: QP0ZCPA

  Default Public Authority: *USE

  Threadsafe: No

The getopt() function returns the next flag letter in the argv list that matches a letter in optionstring. The optarg external variable is set to point to the start of the flag's parameter on return from getopt()

getopt() places the argv index of the next argument to be processed in optind. The optind variable is external. It is initialized to 1 before the first call to getopt().

getopt() can be used to help a program interpret command line flags that are passed to it.


Parameters

argc
(Input) The number of parameters passed by the function.

argv
(Input) The list of parameters passed to the function.

optionstring
(Input) A string of flag letters. The string must contain the flag letters that the program using getopt() recognizes. If a letter is followed by a colon, the flag is expected to have an argument or group of arguments, which can be separated from it by blank spaces.

The special flag "--" (two hyphens) can be used to delimit the end of the options. When this flag is encountered, the "--" is skipped and EOF is returned. This flag is useful in delimiting arguments beginning with a hyphen that are not options.


Authorities

None.


Return Value

EOF getopt() processed all flags (that is, up to the first argument that is not a flag).
'?' getopt() encountered a flag letter that was not included in optionstring. The variable optopt is set to the real option found in argv regardless of whether the flag is in optionstring of not. An error message is printed to stderr. The generation of error messages can be suppressed by setting opterr to 0.


Error Conditions

The getopt() function does not return an error.


Example

The following example processes the flags for a command that can take the mutually exclusive flags a and b, and the flags f and o, both of which require parameters.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.

#include <unistd.h>

int main( int argc, char *argv[] )
{
 int c;
 extern int optind;
 extern char *optarg;
 .
 .
 .
 while ((c = getopt(argc, argv, "abf:o:")) != EOF)
 {
  switch (c)
  {
   case 'a':
    if (bflg)
     errflg++;
    else
     aflg++;
    break;
   case 'b':
    if (aflg)
     errflg++;
    else
     bflg++;
    break;
   case 'f':
    ifile = optarg;
    break;
   case 'o':
    ofile = optarg;
    break;
   case '?':
    errflg++;
  } /* case */
  if (errflg)
  {
   fprintf(stderr, "usage: . . . ");
   exit(2);
  }
 } /* while */
 for ( ; optind < argc; optind++)
 {
  if (access(argv[optind], R_OK))
  {
   .
   .
   .
  }
 } /* for */
}   /* main */


API introduced: V3R6

[ Back to top | UNIX-Type APIs | APIs by category ]