Skip to main content

Parse a required long-option value

To parse a long option that requires an argument, you must specify this requirement when defining the option. The optparse library handles this through the argtype field in the struct optparse_long definition. By setting this field to OPTPARSE_REQUIRED, you instruct the parser to treat the following argument in argv as the value for the current option.

First, you define your long options in an array of struct optparse_long. Each element in this array represents one option and contains its long name, a corresponding short name character, and its argument requirement (OPTPARSE_NONE, OPTPARSE_REQUIRED, or OPTPARSE_OPTIONAL). The array must be terminated by an element with all fields set to zero.

After defining the options, you initialize a struct optparse parser by calling optparse_init with your program's argv. Then, you can call optparse_long to parse the next option. If the parsed option was configured with OPTPARSE_REQUIRED, the parser consumes the next element from argv and places a pointer to it in the optarg field of your struct optparse instance. The function returns the short option character associated with the long option, allowing you to identify which option was found.

The following complete example demonstrates how to configure and parse a long option --value that requires an argument. It initializes the parser, defines the option, calls optparse_long, and then uses assertions to verify that the option was correctly identified and its required value was captured in options.optarg.

#include <assert.h>
#include <string.h>
#include "optparse.h"

int main(void)
{
char *argv[] = {"./program", "--value", "hello", NULL};
struct optparse options;
int opt;
int longindex = -1;
enum optparse_argtype argtype = OPTPARSE_REQUIRED;

const struct optparse_long longopts[] = {
{"value", 'v', argtype},
{0}
};

optparse_init(&options, argv);
opt = optparse_long(&options, longopts, &longindex);

assert(opt == 'v');
assert(longindex == 0);
assert(strcmp(options.optarg, "hello") == 0);

return 0;
}