Parse short options and remaining arguments
To parse command-line arguments, first initialize a struct optparse with your argv. Then, repeatedly call the optparse function to process short options. After all options have been handled, call optparse_arg to retrieve the remaining positional arguments one by one.
The optparse_init function takes a pointer to your struct optparse and the argument vector argv to begin the parsing process. The optparse function then consumes options from argv based on a format string, similar to getopt(). It returns the parsed option character, ? for an unknown option, or -1 when all options have been processed. When optparse returns -1, you can use optparse_arg to get the next available non-option argument. It returns a pointer to the argument string, or NULL if no more arguments are available.
The following example demonstrates this process by initializing a parser, asserting that the short option -a is correctly identified, confirming that no more options are present, and finally asserting that the positional argument positional is retrieved before confirming that all arguments have been processed.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse options;
char *argv[] = {"program", "-a", "positional", NULL};
optparse_init(&options, argv);
assert(optparse(&options, "a") == 'a');
assert(optparse(&options, "a") == -1);
char *arg = optparse_arg(&options);
assert(arg != NULL && strcmp(arg, "positional") == 0);
assert(optparse_arg(&options) == NULL);
return 0;
}