Parse a required long-option value
To parse a command-line option that must be accompanied by a value, such as --file=output.txt, you need to define a long option and specify that its argument is required.
First, initialize a struct optparse parser by passing it and your argv array to the optparse_init function. This struct will hold the parser's state, including the parsed argument value.
Next, you define the accepted long options in an array of struct optparse_long. Each element in this array links a long option string, like "file", to a corresponding short option character. To enforce that a value must be provided, set the argtype field of the struct to OPTPARSE_REQUIRED. This enum optparse_argtype value ensures that the parser expects a value to follow the option.
Finally, call the optparse_long function. When it successfully parses an option that requires an argument, it returns the associated short option character and places a pointer to the argument's string in the optarg field of your struct optparse.
The following complete program demonstrates this process. It configures a single --file option, parses an argv array containing --file=output.txt, and asserts that the option was correctly identified and its value was captured in options.optarg.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"file", 'f', arg_required},
{0} /* Terminator */
};
char *argv[] = {
"program",
"--file=output.txt",
NULL
};
struct optparse options;
optparse_init(&options, argv);
int opt = optparse_long(&options, longopts, NULL);
assert(opt == 'f');
assert(options.optarg != NULL);
assert(strcmp(options.optarg, "output.txt") == 0);
return 0;
}