Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, begin by initializing a struct optparse parser with your argv. Repeatedly call the optparse function to process short options until it returns -1. After all options have been parsed, you can retrieve the remaining positional arguments one by one using the optparse_arg function until it returns NULL.

The optparse function takes an optstring to define the valid option characters. In the example below, the optstring is "b", which declares b as a valid option that does not take an argument.

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

int main(void)
{
struct optparse options;
char *argv[] = {
"program",
"-b",
"positional",
NULL
};

optparse_init(&options, argv);

int option = optparse(&options, "b");
assert(option == 'b');

option = optparse(&options, "b");
assert(option == -1);

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

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

return 0;
}

The process begins by declaring a struct optparse variable and a writable argv array. The optparse_init function is called to prepare the parser. The first call to optparse processes the "-b" argument and returns the option character 'b'. Because no more options are present in argv, the second call to optparse returns -1, signaling the end of option parsing.

With option parsing complete, subsequent calls to optparse_arg retrieve the positional arguments. The first call returns the string "positional". The second call returns NULL because no more positional arguments are left in argv.