Parse a required long-option value
To parse command-line arguments that require a value, such as --file input.txt, you must define the option and specify its argument requirement.
First, you define your long options in an array of struct optparse_long. Each entry in this array specifies the long option name as a string, a corresponding short option character, and the argument requirement. To indicate that an option must be followed by a value, you use the OPTPARSE_REQUIRED member of the enum optparse_argtype.
After defining the options, you initialize the parser by calling optparse_init() with a struct optparse instance and your program's argv. Then, you can call optparse_long() in a loop to process each argument. When optparse_long() successfully parses an option that has a required argument, it stores a pointer to the value in the optarg field of your struct optparse.
The following program demonstrates this process. It configures a single long option --value which requires an argument, parses it from a sample argv, and asserts that the correct value was captured.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
enum optparse_argtype argtype = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"value", 'v', argtype},
{0}
};
char *argv[] = {"myprog", "--value", "payload", NULL};
struct optparse parser;
optparse_init(&parser, argv);
int longindex = -1;
int option = optparse_long(&parser, longopts, &longindex);
assert(option == 'v');
assert(longindex == 0);
assert(strcmp(parser.optarg, "payload") == 0);
return 0;
}
After optparse_long returns, the parser.optarg field points to "payload", which was the argument supplied to the --value option. The function itself returns the corresponding short option character, 'v', and sets the longindex to 0, indicating that the first option in the longopts array was matched.