Skip to main content

Parse a required long-option value

To parse a long option that requires an associated value, such as --file=config.json or --file config.json, you must define the option's argument type as OPTPARSE_REQUIRED. This is done in the argtype field of a struct optparse_long entry.

When optparse_long encounters an option configured this way, it consumes the next element from argv as the option's value. This value is then stored in the optarg field of your struct optparse instance for you to use. If no value is provided, optparse will report an error.

The following example sets up a parser to handle a single long option, --file, which requires a value. It initializes the parser, calls optparse_long to process the arguments, and then asserts that the option and its value were parsed correctly.

#include <assert.h>
#include <string.h>
#include "optparse.h"

int main(void)
{
struct optparse options;
char *argv[] = {"./program", "--file", "config.json", NULL};
enum optparse_argtype argtype = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"file", 'f', argtype},
{0}
};

optparse_init(&options, argv);
int option = optparse_long(&options, longopts, NULL);

assert(option == 'f');
assert(strcmp(options.optarg, "config.json") == 0);

return 0;
}

In this example, the longopts array defines the --file option and associates it with the short option -f. The argtype field is set using a local enum optparse_argtype variable initialized to OPTPARSE_REQUIRED, signaling that a value must follow the option. The array is terminated by a {0} entry, which is required by optparse_long.

After initializing the parser with optparse_init, a single call to optparse_long is made. The function finds the --file option in argv, consumes config.json as its required argument, and returns the corresponding short option, 'f'. The pointer to the argument, "config.json", becomes accessible via options.optarg.