Parse a required long-option value
To parse a long option that requires an associated value, such as --value hello, you must define the option with an argument type of OPTPARSE_REQUIRED. The optparse_long function handles this by consuming the next element from the argv array as the option's argument.
You define your command-line options in a null-terminated array of struct optparse_long. For each option, you specify its long name (e.g., "value"), a corresponding short name (e.g., 'v'), and its argument requirement. After initializing the parser state with optparse_init, a call to optparse_long will attempt to match an option from argv. If it finds a long option that requires an argument, it places a pointer to that argument in the optarg field of your struct optparse and returns the option's short name.
The following program demonstrates how to configure and parse a single long option --value which requires an argument. It initializes a parser, defines the option, and then calls optparse_long once. The assertions verify that the function returns the correct short option 'v' and that options.optarg points to the correct value, "hello".
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse options;
char *argv[] = {"myprogram", "--value", "hello", NULL};
enum optparse_argtype argtype = OPTPARSE_REQUIRED;
const struct optparse_long longopts[] = {
{"value", 'v', argtype},
{0}
};
optparse_init(&options, argv);
int opt = optparse_long(&options, longopts, NULL);
assert(opt == 'v');
assert(options.optarg != NULL);
assert(strcmp(options.optarg, "hello") == 0);
assert(options.optind == 3);
return 0;
}
In this example, the longopts array configures the --value option. Its argtype field is set to OPTPARSE_REQUIRED, making its value mandatory. When optparse_long is called, it successfully parses --value and its argument "hello". The parser also updates its index, options.optind, to 3, indicating that it has processed the program name, the option, and its value, and is ready to parse the next argument.