Parse short options and remaining arguments
To parse command-line arguments, separating short options from positional arguments, use a struct optparse to maintain the parsing state. First, initialize the parser with optparse_init(), then repeatedly call optparse() to handle options, and finally, call optparse_arg() to retrieve the remaining arguments.
The following example demonstrates how to parse an argument list containing one short option (-a) and one positional argument (positional). It uses assertions to verify that the option and argument are parsed correctly.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void) {
char *argv[] = {
"./myprogram",
"-a",
"positional",
NULL
};
struct optparse options;
optparse_init(&options, argv);
assert(optparse(&options, "a") == 'a');
assert(optparse(&options, "a") == -1);
const char *arg = optparse_arg(&options);
assert(arg != NULL && strcmp(arg, "positional") == 0);
assert(optparse_arg(&options) == NULL);
return 0;
}
The process begins by initializing a struct optparse and a char *argv[] array that holds the command-line arguments. The optparse_init() function is called with the address of the options struct and the argv array to set up the initial parser state.
The optparse() function parses the options. It takes the options struct and a string of valid option characters. The first call correctly identifies and returns the character 'a'. The second call returns -1, indicating that all options have been processed.
After optparse() returns -1, optparse_arg() is called to retrieve the remaining positional arguments. The first call returns the string "positional". The second call returns NULL, signifying that there are no more arguments to process.