Parse a required long-option value
'''
To parse a long option that requires a value, such as --file=output.txt, you must define the option's expected behavior in an array of struct optparse_long objects. Each element in this array specifies a long option's name, its corresponding short name, and its argument requirements.
For an option that must have a value, set the argtype field of its struct optparse_long to OPTPARSE_REQUIRED. The longname field is the string for the long option without the preceding --, and shortname is the character for the equivalent short option.
The parsing process begins by initializing a struct optparse parser state with optparse_init, providing it with the command-line arguments (argv). You then call optparse_long, passing the parser, the long options array, and a pointer for the index of the matched option. If a defined long option is found, optparse_long returns its shortname and makes the corresponding value available via the optarg field of the struct optparse.
The following example demonstrates how to configure and parse a single --file option that requires a value. It defines the long option, initializes the parser, and then calls optparse_long to process the argument. Assertions are used to verify that the option is correctly identified by its short name 'f' and that its value is successfully stored in parser.optarg.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse_long longopts[] = {
{"file", 'f', OPTPARSE_REQUIRED},
{0}
};
char *argv[] = {
"myprogram",
"--file=output.log",
NULL
};
struct optparse parser;
optparse_init(&parser, argv);
int opt = optparse_long(&parser, longopts, NULL);
assert(opt == 'f');
assert(parser.optarg != NULL);
assert(strcmp(parser.optarg, "output.log") == 0);
return 0;
}
'''