getopt_long() — Command long option parsing
Standards
| Standards / Extensions | C or C++ | Dependencies |
|---|---|---|
| z/OS® UNIX | both |
Format
#define _XPLATFORM_SOURCE
#include <stdio.h>
#include <getopt.h>
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex);
General description
getopt_long() function is similar to getopt() except that it
accepts long options, which begin with two dashes. (If the program accepts only long options,
optstring must be specified as an empty string
(""), not NULL.) Long option names might be abbreviated if the abbreviation is
unique or is an exact match for some defined option. A long option might take a parameter of the
form --option=arg or --option arg.
longopts is a pointer to the first element of an array of
struct option that is declared in <getopt.h>.
struct option {
const char *name;
int has_arg;
int *flag;
int val;
};
name- The name of the long option.
has_arg- This argument has one of the following values:
no_argument(or 0) if the option does not take an argument.required_argument(or 1) if the option requires an argument.optional_argument(or 2) if the option takes an optional argument. In this case,getopt_long()can only parse the argument setting in the form of--option=arg.
flag- Specifies how results are returned for a long option. If
flagis NULL,getopt_long()returnsval. Otherwise,getopt_long()returns 0, andflagpoints to a variable that is set tovalif the option is found, but left unchanged if the option is not found. val- The value to return or to load into the variable that is pointed to by
flag.
The last element of the array must be filled with zeros.
If longindex is not NULL, it points to a variable that is set
to the index of the long option that is relative to longopts.
Returned value
If successful, getopt_long() returns the option character if a short option is
recognized. For a long option, it returns val if flag is NULL;
otherwise it returns 0 and stores val in the location pointed to by
flag.
If getopt_long() encounters an unknown option, '?' is returned.
If getopt_long() encounters an option with a missing argument, the return value
depends on the first character in optstring: if it is
':', ':' is returned; otherwise, '?' is
returned.
If an option is specified with an argument but the option is defined to be
no_argument in longopts,
getopt_long() returns '?'.
If getopt_long() detects a missing argument or an option string not in
longopts, it writes an error message to stderr to describe the
option character or string in error and the invoking program.
getopt_long() returns -1 when all command line arguments are parsed or an
unexpected error is encountered in the command line. getopt_long() does not return
any errno values.
If getopt_long() detects a missing argument or an option string not in
longopts, it writes an error message to stderr
describing the option character or string in error and the invoking program.