Skip to main content

Parse a required long-option value

''' When parsing command-line arguments, you often need to handle long options that require a value, such as --file=input.txt. The optparse library manages this by checking an option's defined argument type.

To define an option that must have an argument, you create an array of struct optparse_long and set the argtype field to OPTPARSE_REQUIRED for that option. This signals to the parser that a value must follow the option name.

You first initialize the parser state by passing your argv to the optparse_init function. Then, you call optparse_long in a loop, providing it with your option definitions. When optparse_long finds an option that requires an argument, it parses the accompanying value and stores a pointer to it in the optarg field of your struct optparse instance. The function itself returns the short name character associated with the long option, allowing you to identify which option was found.

The following example demonstrates this process. It defines a single long option --file that requires a value, parses an argv array containing that option, and then asserts that the parser correctly identified the option and extracted its value.

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

int main(void)
{
enum optparse_argtype arg_required = OPTPARSE_REQUIRED;
struct optparse_long longopts[] = {
{"file", 'f', arg_required},
{0}
};

char *argv[] = {
"prog", "--file=input.txt", NULL
};

struct optparse options;
optparse_init(&options, argv);

int longindex;
int opt = optparse_long(&options, longopts, &longindex);

assert(opt == 'f');
assert(options.optarg != NULL);
assert(strcmp(options.optarg, "input.txt") == 0);

return 0;
}

'''