Parse a required long-option value
To parse a command-line option that requires an associated value, such as --file=output.txt or --file output.txt, you must define the option and specify that its argument is mandatory.
The process begins when you initialize the parser by passing your argv to the optparse_init function. This prepares a struct optparse to track parsing state.
Next, you define the long options your program accepts in a null-terminated array of struct optparse_long. For each option, you specify its name (e.g., "file"), a corresponding short name character, and its argument requirements. To enforce that an argument must be present, you set the argtype field to OPTPARSE_REQUIRED, a value from the optparse_argtype enum.
When you call the optparse_long function, it inspects the next argument from the argv provided during initialization. If it matches a long option that you defined with OPTPARSE_REQUIRED, the function captures the associated value. This value is then made available as a string pointer in the optarg field of your struct optparse. The function itself returns the integer value of the shortname you associated with the long option, allowing you to identify which option was found.
#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}
};
char *argv[] = {
"myprogram",
"--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;
}