Parse a required long-option value
To parse command-line options that require a value, such as --file <path>, you define the option's requirements in an array of struct optparse_long. Each element in this array describes one long option, its corresponding short option character, and how it handles an argument.
To specify that an option must be followed by a value, you set the argtype field of its struct optparse_long entry to OPTPARSE_REQUIRED. The optparse_argtype enum provides the possible values for this field. The array of long options must always be terminated by an entry filled with zeros.
After defining your options, you initialize a struct optparse parser by passing it your argv array with optparse_init. The argv array must be NULL-terminated.
Calling optparse_long then parses the next option from argv. If it finds an option that requires an argument, it consumes the next element from argv as its value. This value is then available in the optarg field of your struct optparse instance. The function returns the short option character associated with the long option it found.
The following example demonstrates how to configure and parse a --value option that requires an argument. It initializes the parser, calls optparse_long to process the arguments, and then asserts that the correct short option was identified and its value was successfully captured in options.optarg.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
enum optparse_argtype argtype = OPTPARSE_REQUIRED;
const struct optparse_long longopts[] = {
{"value", 'v', argtype},
{0, 0, 0}
};
char *argv[] = {
"program",
"--value",
"hello",
NULL
};
struct optparse options;
optparse_init(&options, argv);
int opt = optparse_long(&options, longopts, NULL);
assert(opt == 'v');
assert(strcmp(options.optarg, "hello") == 0);
return 0;
}