Parse a required long-option value
To parse a long option that must be accompanied by a value, such as --color red, you define the option using a struct optparse_long and specify that its argument is mandatory.
The argtype field in the struct optparse_long entry for your option controls this behavior. By setting this field to OPTPARSE_REQUIRED, you instruct the parser to expect a value immediately following the option. If the value is missing, parsing will fail.
After defining the options, you initialize the parser state with optparse_init() and then call optparse_long() to process the arguments. When optparse_long() successfully parses an option with a required argument, it returns the corresponding short option character and places a pointer to the argument's string value in the optarg field of the optparse struct.
The following complete example demonstrates how to configure a --color option that requires a value. It initializes a parser, processes an argv array containing "--color", "red", and then uses assert() to verify that the parser correctly identifies the option and captures its value.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse options;
char *argv[] = {"prog", "--color", "red", NULL};
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"color", 'c', arg_required},
{0}
};
optparse_init(&options, argv);
int opt = optparse_long(&options, longopts, NULL);
assert(opt == 'c');
assert(strcmp(options.optarg, "red") == 0);
return 0;
}
In this example, the longopts array defines the --color option with the short name 'c' and marks its argument as required. The call to optparse_long() processes the arguments, returning 'c' and setting options.optarg to point to the string "red", confirming that the required value was successfully parsed.