Parse short options and remaining arguments
'''
To parse command-line arguments, use a struct optparse to maintain the parser state. First, initialize the structure by passing your argv to the optparse_init() function. You can then process short options and positional arguments.
The following example parses an argument list containing one short option (-n) and one positional argument (hello). It uses assert() to verify that the option is correctly identified and that the subsequent positional argument is retrieved.
#include <assert.h>
#include <string.h>
#include "optparse.h"
int main(void)
{
struct optparse options;
char *argv[] = { "program", "-n", "hello", NULL };
optparse_init(&options, argv);
/* Parse the -n option. */
assert(optparse(&options, "n") == 'n');
/* Assert that option parsing is complete. */
assert(optparse(&options, "n") == -1);
/* Retrieve the positional argument. */
char *arg = optparse_arg(&options);
assert(strcmp(arg, "hello") == 0);
/* Assert that there are no more positional arguments. */
assert(optparse_arg(&options) == NULL);
return 0;
}
To process the arguments, first repeatedly call the optparse() function to handle all short options. This function takes the optparse struct and a string of supported option characters. It returns the option character found or -1 once all arguments starting with a hyphen have been processed.
After the options have been handled, call optparse_arg() to retrieve the remaining positional arguments one by one. This function returns a pointer to the next argument string (char *). When no more arguments are available, it returns NULL.
'''