|
|
The Args component models the command line arguments with which a program is invoked by a single class ``Args''. The set of allowed options is specified to Args using exactly the same syntax as with getopt(3C). Assume, for example, we wish to accept the above -c, -o, and -O options of the cc command. The code to do this is as follows:
#include <Args.h>main(int argc, const char*const* argv) { Args args(argc, argv, "co:O"); // ... }
Notice that like getopt(3C), value-taking options are specified with a following `:' in the option string.
Discovering which options were set by the user invoking the program, and their corresponding values, is easy. In the following code, we define a few global variables to store the settings of the command line arguments:
int compile_only = 0; int optimize = 0; const char* output_filename = "a.out";main(int argc, const char*const* argv) { Args args(argc, argv, "co:O"); compile_only = args.isset('c'); optimize = args.isset('O'); if (args.isset('o')) output_filename = args.value('o'); // ... }
The (non-option) arguments to a program can be processed using an ``arguments iterator''. This is an object which, given an Args object, returns every (non-option) argument in the order they appeared on the command line. Here is the code to retrieve the list of files for cc to compile:
extern void compile(const char*);main(int argc, const char*const* argv) { Args args(argc, argv, "co:O"); // ... Argsiter ai(args); const char* filename; while (ai.next(filename)) compile(filename); }
Notice that the arguments are returned through the reference parameter of next(). The return value of next is true as long as there was another argument.