OptionsScan - Command-Line Options Scan
An OptionsScan object represents the scan of a set of UNIX-style
command line arguments. OptionsScan objects can scan and parse:
-a"
-o file"
-readonly"
-list file"
> outputFile"
The scanning algorithm used by the OptionsScan class allows
word options to be abbreviated on the command line. For example, the
"-list file" word option in (4) above can be
entered on the command line as "-l file",
"-li file", "-lis file", or
"-list file". If the one-character abbreviation of a word
conflicts with a single-letter option, the single-letter option takes priority.
The following command line
% program -a -o objectFile -readonly -list file
would be scanned and parsed as follows using the OptionsScan class:
#include "OptionsScan.h"
char *argument ;
int option ;
OptionsScan *scan = new OptionsScan ("ao:{readonly}{object:}") ;
scan->Start (argc, argv) ;
while (option = scan->Get (&argument)) {
switch (option) {
case 1: ... process "-a" option ...
case 2: ... process "-o file" option argument ...
case 3: ... process "-readonly" option ...
case 4: ... process "-list file" option ...
case OptionsScan::NONOPT:
... process non-option argument ...
case OptionsScan::OPTERR:
... invalid option or missing argument ...
}
}
Applications that will scan multiple command lines using the same set of
allowable options can cache the original scan context, resetting it for each
new command line (represented by a new argc/argv
set of arguments):
static char *optionList[] = { // Command line options.
"a", "o:", "{readonly}", "{object:}", 0
} ;
static OptionsScan *scan = new OptionsScan (optionList) ;
...
for (... each new ARGC/ARGV set of arguments ...) {
scan->Start (argc, argv) ;
while (option = scan->Get (&argument)) {
... process options ...
}
}
Note in the example above that the valid command line options are specified in list form rather than in-line.
Note: This class is a quick C++ implementation of my
OPT_UTIL C package. As such, large blocks of comments and code
were simply cut and pasted from the C package. It's not pretty, but it seems
to work and it provides a reasonably clean interface for scanning command line
arguments.
OptionsScan() - creates an options scan from an inline options string.
OptionsScan() - creates an options scan from an array of options strings.
~OptionsScan() - destroys an options scan.
Errors() - redirects error output.
Get() - gets the next option and/or argument from the command line.
NameOf() - returns an option's full name.
Position() - returns the index of the last argument scanned.
Position() - sets the index of the next argument to be scanned.
Start() - begin scanning a command line string.
Start() - begin scanning an argc/argv command line.
Init() - initializes an options scan's internal state.
OptionsScan.cpp
OptionsScan.h