GETOPT_LONG(3) | NetBSD Library Functions Manual | GETOPT_LONG(3) |
int
getopt_long(int argc, char * const *argv, const char *optstring, struct option *long_options, int *index);
In the second mechanism, a long option sets a flag in the option structure passed, or will store a pointer to the command line argument in the option structure passed to it for options that take arguments. Additionally, the long option's argument may be specified as a single argument with an equal sign, e.g.
myprogram --myoption=somevalue
When a long option is processed the call to getopt_long() will return 0. For this reason, long option processing without shortcuts is not backwards compatible with getopt(3).
It is possible to combine these methods, providing for long options processing with short option equivalents for some options. Less frequently used options would be processed as long options only.
Abbreviated long option names are accepted when getopt_long() processes long options if the abbreviation is unique. An exact match is always preferred for a defined long option.
The getopt_long() call requires a structure to be initialized describing the long options. The structure is:
struct option { char *name; int has_arg; int *flag; int val; };
The name field should contain the option name without the leading double dash.
The has_arg field should be one of:
If flag is not NULL, then the integer pointed to by it will be set to the value in the val field. If the flag field is NULL, then the val field will be returned. Setting flag to NULL and setting val to the corresponding short option will make this function act just like getopt(3).
If the index field is not NULL, the integer it points to will be set to the index of the long option in the long_options array.
The last element of the long_options array has to be filled with zeroes (see EXAMPLES section).
extern char *optarg; extern int optind; int bflag, ch, fd; int daggerset; /* options descriptor */ static struct option longopts[] = { { "buffy", no_argument, 0, 'b' }, { "fluoride", required_argument, 0, 'f' }, { "daggerset", no_argument, &daggerset, 1 }, { NULL, 0, NULL, 0 } }; bflag = 0; while ((ch = getopt_long(argc, argv, "bf:", longopts, NULL)) != -1) switch (ch) { case 'b': bflag = 1; break; case 'f': if ((fd = open(optarg, O_RDONLY, 0)) < 0) { (void)fprintf(stderr, "myname: %s: %s\n", optarg, strerror(errno)); exit(1); } break; case 0: if(daggerset) { fprintf(stderr,"Buffy will use her dagger to " "apply fluoride to dracula's teeth\n"); } break; case '?': default: usage(); } argc -= optind; argv += optind;
The argv argument is not really const.
July 2, 2007 | NetBSD 5.99 |