Parse a required long-option value
When your C application needs to accept command-line arguments with values, such as specifying a configuration file with --file config.txt, the optparse library provides a structured way to define and parse them. Parsing a long option that requires a value involves initializing a parser, defining the expected options, and then processing the input array.
To accomplish this, you use three main components: the optparse_init function to prepare the parser, a struct optparse_long array to define your command-line options, and the optparse_long function to perform the parsing. For an option to require a value, you must specify OPTPARSE_REQUIRED from the optparse_argtype enum in its definition.
The following program demonstrates how to configure a parser for a single --file option that requires an argument. It initializes a struct optparse with a sample argv, calls optparse_long to process it, and then uses assertions to verify that the option was correctly identified and its value captured in the optarg field.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse parser;
int opt;
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long long_options[] = {
{"file", 'f', arg_required},
{0} /* Terminating entry */
};
char *argv[] = {
"myprogram",
"--file",
"config.ini",
NULL
};
optparse_init(&parser, argv);
opt = optparse_long(&parser, long_options, NULL);
assert(opt == 'f');
assert(strcmp(parser.optarg, "config.ini") == 0);
return 0;
}
In this example, the long_options array defines the accepted long options. Each entry contains the long name (e.g., "file"), a corresponding short name character ('f'), and the argument requirement. The array must be terminated by a zero-filled entry like {0}.
The optparse_init function associates the parser with your argv array. The subsequent call to optparse_long attempts to parse the next option. Upon finding --file, it consumes the next element, "config.ini", as its value because the option was defined with OPTPARSE_REQUIRED. The function returns the associated short character, 'f', and stores a pointer to the value "config.ini" in the parser.optarg field.