Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, initialize a parser, loop through the options, and then retrieve the remaining arguments. The optparse library provides a simple interface for this common task. The following example demonstrates how to parse a single short option (-a) and a single positional argument (myargument).

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

int main(void) {
char *argv[] = {"myprogram", "-a", "myargument", NULL};

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

int option;
while ((option = optparse(&options, "a")) != -1) {
if (option == 'a') {
/* The -a option was found. */
} else {
/* Unrecognized option. */
assert(0);
}
}

char *arg = optparse_arg(&options);
assert(strcmp(arg, "myargument") == 0);

arg = optparse_arg(&options);
assert(arg == NULL);

return 0;
}

The process begins by setting up a struct optparse and initializing it by calling optparse_init() with your argv array. This prepares the parser to scan the arguments.

A while loop calling optparse() repeatedly will process each option. This function takes the option string (e.g., "a") and returns the character for each option it finds. When no more options are left, it returns -1, terminating the loop.

After the option-parsing loop is complete, you can retrieve the remaining positional arguments one by one by calling optparse_arg(). In this example, it is called first to get the string "myargument" and a second time to confirm that no more arguments remain, at which point it returns NULL.