Parse a required long-option value
To parse a long option that requires a value, such as --output file.txt, you must define the option with the OPTPARSE_REQUIRED argument type. This ensures that optparse correctly associates the following argument on the command line as the value for that option.
The primary mechanism for defining long options is an array of struct optparse_long structs. Each struct in the array defines a long option, its short-option equivalent (if any), and its argument requirement. This array must be terminated by a zero-filled struct.
First, you initialize the parser state by calling optparse_init() with your argv. Then, you can call optparse_long() to parse the next option. When optparse_long() finds an option that requires an argument, it will populate the optarg field of your struct optparse with a pointer to the value.
The following program demonstrates how to configure a long option --output that requires a value. It initializes the parser, calls optparse_long once, and then asserts that the function returned the correct short option character and that the parser.optarg field points to the expected value, "out.txt".
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void) {
struct optparse parser;
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long opts[] = {
{"output", 'o', arg_required},
{0}
};
char *argv[] = {
"program",
"--output",
"out.txt",
NULL
};
optparse_init(&parser, argv);
int option;
option = optparse_long(&parser, opts, NULL);
assert(option == 'o');
assert(strcmp(parser.optarg, "out.txt") == 0);
return 0;
}
In this example, the opts array defines the --output option with a short alias of -o and specifies arg_required (which is OPTPARSE_REQUIRED) as its argument type. After optparse_long() successfully parses the --output out.txt pair, it returns the short option 'o' and sets parser.optarg to point to the string "out.txt" within the argv array.