Parse short options and remaining arguments
To parse command-line arguments with optparse, you first initialize a parser with a NULL-terminated argv array, then repeatedly call optparse to handle short options, and finally call optparse_arg to retrieve any remaining positional arguments.
The optparse_init function prepares a struct optparse instance for parsing. After initialization, you can loop over optparse until it returns -1, which signals that all option arguments (those beginning with a hyphen) have been processed. Following that, you can loop over optparse_arg until it returns NULL to get the non-option, positional arguments.
The following example demonstrates parsing an argument list containing one short option (-a) and one positional argument (argument). It uses assertions to verify that each function call returns the expected value, confirming the option is found, the end of options is detected, the positional argument is retrieved, and finally, the end of arguments is reached.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "optparse.h"
int main(void) {
struct optparse parser;
char *argv[] = {
"./program",
"-a",
"argument",
NULL
};
optparse_init(&parser, argv);
/* First call finds the short option */
assert(optparse(&parser, "a") == 'a');
/* Second call finds no more options */
assert(optparse(&parser, "a") == -1);
/* First call retrieves the positional argument */
assert(strcmp(optparse_arg(&parser), "argument") == 0);
/* Second call finds no more arguments */
assert(optparse_arg(&parser) == NULL);
return 0;
}
First, optparse_init is called with a pointer to the parser struct and the argv array. The first call to optparse with the optstring "a" successfully finds and returns the character a. The second call returns -1, indicating no more options are available for parsing. Subsequently, the first call to optparse_arg returns the string "argument". The final call to optparse_arg returns NULL, signifying that all positional arguments have been processed.