Skip to main content

Parse short options and remaining arguments

To parse command-line arguments with optparse, you initialize a struct optparse with your argv array, then repeatedly call the optparse function to handle options, and finally call optparse_arg to retrieve any leftover positional arguments.

The following example demonstrates this workflow by parsing an argument list containing one short option (-a) and one positional argument.

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

int main(void)
{
char *argv[] = {"myprogram", "-a", "positional", NULL};
struct optparse parser;
optparse_init(&parser, argv);

/* Parse the short option */
assert(optparse(&parser, "a") == 'a');

/* Assert that option parsing is finished */
assert(optparse(&parser, "a") == -1);

/* Assert the positional argument's value */
assert(strcmp(optparse_arg(&parser), "positional") == 0);

/* Assert that no more arguments remain */
assert(optparse_arg(&parser) == NULL);

return 0;
}

This example first initializes a struct optparse and a sample argv array. The optparse_init function prepares the parser for use.

The first call to optparse processes the -a option from the argv array, returning its character value 'a'. Because the option string "a" does not have a following colon, the option takes no argument.

After all options are parsed, optparse returns -1. The code asserts this to confirm that no options remain.

Finally, the optparse_arg function is called to retrieve the remaining arguments. The first call returns the string "positional", and the second call returns NULL, indicating that all arguments have been processed.