Skip to main content

Parse a required long-option value

To parse a long option that requires a value, such as --file=input.txt, you use the optparse_long function. You must first define the option and specify that its argument is mandatory.

This is done by creating an array of struct optparse_long and setting the argtype field to OPTPARSE_REQUIRED for the relevant option. This enum value, defined in the optparse.h header, tells optparse_long that an error should be reported if the option is present but the value is missing.

The overall process involves initializing a struct optparse parser state with optparse_init, defining your long options, and then calling optparse_long to parse the arguments. When optparse_long successfully finds an option with a required argument, it returns the option's short-name equivalent and places a pointer to the argument's value in the optarg field of the struct optparse.

The following program demonstrates this by parsing an argv array containing --file=input.txt. It initializes the parser, defines the --file option with OPTPARSE_REQUIRED, calls optparse_long, and then uses assertions to verify that the option was correctly identified and that its value was captured.

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

int main(void)
{
struct optparse options;
char *argv[] = {"prog", "--file=input.txt", NULL};
int option;
int longindex = -1;

enum optparse_argtype arg_type = OPTPARSE_REQUIRED;

struct optparse_long longopts[] = {
{"file", 'f', arg_type},
{0}
};

optparse_init(&options, argv);

option = optparse_long(&options, longopts, &longindex);

assert(option == 'f');
assert(longindex == 0);
assert(options.optarg != NULL);
assert(strcmp(options.optarg, "input.txt") == 0);

return 0;
}

In the example, the longopts array configures a single long option, "file", which corresponds to the short option f and requires an argument. After calling optparse_long, the assertions confirm that it returns 'f' and that options.optarg points to the string "input.txt", successfully parsing the option and its required value.