Parse short options and remaining arguments
To parse simple command-line arguments, you can use a combination of optparse_init, optparse, and optparse_arg. You first initialize a struct optparse parser with your argv, then repeatedly call optparse to handle short options, and finally call optparse_arg to retrieve any remaining positional arguments.
The following example demonstrates how to parse an argument list containing one short option (-a) and one positional argument (argument).
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
char *argv[] = {
"./program",
"-a",
"argument",
NULL
};
struct optparse parser;
optparse_init(&parser, argv);
int option = optparse(&parser, "a");
assert(option == 'a');
option = optparse(&parser, "a");
assert(option == -1);
char *arg = optparse_arg(&parser);
assert(strcmp(arg, "argument") == 0);
arg = optparse_arg(&parser);
assert(arg == NULL);
return 0;
}
The process starts by initializing the parser state by calling optparse_init with a pointer to a struct optparse and the argv array. The argv array must be NULL-terminated.
You then call the optparse function until it has processed all options. In the example, the first call correctly returns the character 'a' for the -a option. The second call returns -1, signaling that option parsing is complete.
After optparse returns -1, you can retrieve the remaining non-option arguments. The optparse_arg function is used for this purpose. The first call returns the "argument" string. The next call returns NULL because there are no more arguments to process.