Skip to main content

Parse short options and remaining arguments

To parse command-line arguments, you must first initialize a struct optparse parser state. The optparse_init() function prepares the parser, taking a pointer to your struct optparse and the argv array from your main function.

Once initialized, call the optparse() function repeatedly to process short options. This function takes the parser and a string of valid option characters (the optstring). It returns the option character it found or -1 when all options prefixed with - have been parsed. After the optparse() loop finishes, you can retrieve the remaining positional arguments by calling optparse_arg() until it returns NULL.

The following example demonstrates parsing one short option (-a) and one positional argument (pos_arg). It uses assert() to verify that the option is correctly identified, that option parsing terminates, and that the positional argument is retrieved as expected.

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

int main(void)
{
char *argv[] = {"myprog", "-a", "pos_arg", 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, "pos_arg") == 0);

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

return 0;
}

In this example, the first call to optparse() correctly returns the character 'a'. The second call returns -1, confirming that no more options are present. Following this, the first call to optparse_arg() returns the string "pos_arg". The second call returns NULL, indicating that all positional arguments have been processed. The argv array passed to optparse_init() must be a writable, NULL-terminated array of strings.