Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, first separate short options from positional arguments. The optparse library manages the parsing state within a struct optparse.

Start by initializing the parser with your program's arguments by calling optparse_init(). This function takes a pointer to your struct optparse and the argv array.

Once initialized, process the options by repeatedly calling optparse(). This function returns the next option character from the optstring you provide. When it has processed all options, it returns -1.

After the options have been parsed, retrieve the remaining positional arguments by calling optparse_arg() in a loop until it returns NULL.

The following example demonstrates parsing one short option (-a) and one positional argument.

#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);

/* Parse options */
int option;
option = optparse(&options, "a");
assert(option == 'a');
option = optparse(&options, "a");
assert(option == -1);

/* Parse arguments */
char *arg;
arg = optparse_arg(&options);
assert(strcmp(arg, "argument") == 0);
arg = optparse_arg(&options);
assert(arg == NULL);

return 0;
}