Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, first initialize a struct optparse parser state. The optparse_init() function takes a pointer to your options struct and a NULL-terminated argv array to begin.

After initialization, call optparse() to extract each short option. When optparse() returns -1, all options have been processed. You can then call optparse_arg() to retrieve the remaining positional arguments one by one until it returns NULL.

The following complete example demonstrates parsing one short option (-a) and one positional argument (argument). It uses assertions to verify that the option and argument are parsed correctly, and to confirm that the parser correctly reports the end of both options and arguments.

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

int main(void)
{
char *argv[] = {
"program",
"-a",
"argument",
NULL
};
struct optparse options;
optparse_init(&options, argv);
assert(optparse(&options, "a") == 'a');
assert(optparse(&options, "a") == -1);
assert(strcmp(optparse_arg(&options), "argument") == 0);
assert(optparse_arg(&options) == NULL);
return 0;
}

The first call to optparse() successfully parses and returns the character 'a'. The second call returns -1 because no options remain. Following this, the first call to optparse_arg() returns the positional argument "argument". The final call to optparse_arg() returns NULL, signifying that all positional arguments have been consumed.