Parse a required long-option value
To parse a long option that requires a value, such as --file=output.txt, you define the option in a struct optparse_long array and specify that its argument is mandatory.
The argtype field in the struct optparse_long definition controls this behavior. By setting this field to OPTPARSE_REQUIRED, you instruct the optparse_long function to expect a value for the option. When a matching option is found in the arguments, its value is stored in the optarg field of your struct optparse instance.
The following program demonstrates how to configure and parse a single long option --version that requires a value. It declares a local enum optparse_argtype variable, initializes a parser with optparse_init, defines the --version option using that variable, and then calls optparse_long to process the arguments. After the call, it asserts that the function returned the correct short option character 'v' and that the optarg field contains the expected value, "1.0".
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"version", 'v', arg_required},
{0}
};
char *argv[] = {
"program",
"--version=1.0",
NULL
};
struct optparse options;
optparse_init(&options, argv);
int opt = optparse_long(&options, longopts, NULL);
assert(opt == 'v');
assert(options.optarg != NULL);
assert(strcmp(options.optarg, "1.0") == 0);
return 0;
}
Parsing is driven by the longopts table. Each entry defines a long option string, a corresponding short option character to return upon a match, and an optparse_argtype value. The table must be terminated by an entry where all fields are zero, which is concisely written as {0}.
The optparse_init function prepares the options struct for parsing by associating it with your argv array. The optparse_long function then attempts to parse one option, returning the short option identifier ('v' in this case) on success. The argument to the option is then available at options.optarg.