Parse a required long-option value
To parse a command-line option that must be accompanied by a value, such as --value test, you define the option and specify its argument requirement.
First, you must initialize the parser by passing your application's argc and argv to the optparse_init function. This prepares a struct optparse for parsing.
Next, you define all accepted long options in an array of struct optparse_long. Each element in this array links a long option string (like "value") to a short option character (like 'v') and specifies the argument requirement via the argtype field. To make the value mandatory, you set this field to OPTPARSE_REQUIRED, a value from the optparse_argtype enum. The longopts array must be terminated by a zero-filled struct.
With the setup complete, you can call optparse_long in a loop. When it finds a matching option, it returns the corresponding short option character. The option's value, which optparse requires to be present, is then accessible as a string in the optarg field of your struct optparse.
The following complete program demonstrates this flow. It defines a --value option that requires an argument, parses it from a sample argv array, and asserts that the correct short option ('v') is returned and that options.optarg points to the correct value ("test").
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse options;
char *argv[] = {"./program", "--value", "test", NULL};
enum optparse_argtype argtype = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"value", 'v', argtype},
{0}
};
optparse_init(&options, argv);
int opt;
int longindex = -1;
opt = optparse_long(&options, longopts, &longindex);
assert(opt == 'v');
assert(longindex == 0);
assert(strcmp(options.optarg, "test") == 0);
return 0;
}