Parse short options and remaining arguments
To parse command-line arguments, first initialize a struct optparse parser by passing its address and your argv array to optparse_init. The argv array must be writable and terminated by a NULL pointer.
With the parser initialized, you can iteratively parse short options by calling the optparse function. This function takes the parser and an optstring (a string of valid option characters) as arguments. It returns the character for each option found. When optparse returns -1, all command-line options have been processed.
After you have parsed the options, call optparse_arg to retrieve the remaining positional arguments one at a time. This function returns a pointer to the next argument string. When no more arguments are left, optparse_arg returns NULL.
The following example demonstrates this complete process. It initializes a parser with an argv containing one short option (-a) and one positional argument, then uses assertions to verify that both are parsed correctly.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
char *argv[] = {"program", "-a", "positional", 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, "positional") == 0);
arg = optparse_arg(&options);
assert(arg == NULL);
return 0;
}