Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, separating short options from positional arguments, initialize a parser and then use optparse and optparse_arg to process the argv array. The optparse function extracts options, and optparse_arg retrieves any remaining arguments after all options have been handled.

The following example demonstrates how to parse an argv array containing one short option (-a) and one positional argument (argument).

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

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

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

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

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

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

return 0;
}

First, a struct optparse is initialized by calling optparse_init. This function takes a pointer to your struct and the argv array you intend to parse. The argv array must be writable and NULL-terminated.

Next, the optparse function is called to get the next option. It returns the character for a valid option, in this case 'a'. When called again after all options have been processed, it returns -1 to signal that parsing is complete.

After optparse returns -1, you can retrieve the remaining positional arguments. The optparse_arg function returns a pointer to the next available argument string. In the example, it first returns "argument". When no more arguments are left, optparse_arg returns NULL.