Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, you first initialize a struct optparse parser with your argc and argv vectors. Then, you can iteratively process short options and, subsequently, any remaining positional arguments.

The optparse function is called in a loop to handle options. When it returns -1, all options have been processed, and you can then use optparse_arg to retrieve the positional arguments.

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

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

int option;
option = optparse(&parser, "a");
assert(option == 'a');
option = optparse(&parser, "a");
assert(option == -1);

char *arg;
arg = optparse_arg(&parser);
assert(strcmp(arg, "positional") == 0);
arg = optparse_arg(&parser);
assert(arg == NULL);

return 0;
}

The process begins by setting up a struct optparse and initializing it with optparse_init(), passing it the argument vector.

Each call to optparse() attempts to parse the next option from the argv supplied during initialization. It returns the character of the option that was found. In the example, the first call correctly returns 'a'. Once all arguments starting with - have been processed, optparse() returns -1, signaling that it is time to handle positional arguments.

After option parsing is complete, optparse_arg() is used to retrieve the remaining arguments in order. It returns a pointer to the argument string. When no more arguments are available, it returns NULL.