STXXL  1.4.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Command Line Parser

STXXL now contains a rather sophisticated command line parser for C++, cmdline_parser, which enables rapid creation of complex command line constructions. Maybe most importantly for application with external memory: the parser will recognize byte sizes with SI/IEC suffixes like '2 GiB' and transform it appropriately.

#include <stxxl/cmdline>
int main(int argc, char* argv[])
{
// add description and author
cp.set_description("This may some day be a useful program, which solves "
"many serious problems of the real world and achives "
"global peace.");
cp.set_author("Timo Bingmann <[email protected]>");
// add an unsigned integer option --rounds <N>
unsigned int rounds = 0;
cp.add_uint('r', "rounds", "N", "Run N rounds of the experiment.", rounds);
// add a byte size argument which the user can enter like '1gi'
stxxl::uint64 a_size = 0;
cp.add_bytes('s', "size", "Number of bytes to process.", a_size);
// add a required parameter
std::string a_filename;
cp.add_param_string("filename", "A filename to process", a_filename);
// process command line
if (!cp.process(argc, argv))
return -1; // some error occurred and help was always written to user.
std::cout << "Command line parsed okay." << std::endl;
// output for debugging
// do something useful
}

When running the program above without arguments, it will print:

$ ./cmdline
Missing required argument for parameter 'filename'

Usage: ./cmdline [options] <filename>

This may some day be a useful program, which solves many serious problems of
the real world and achives global peace.

Author: Timo Bingmann <[email protected]>

Parameters:
  filename  A filename to process
Options:
  -r, --rounds N  Run N rounds of the experiment.
  -s, --size      Number of bytes to process.

Nice output, notice the line wrapping of the description and formatting of parameters and arguments. These too are wrapped if the description is too long.

We now try to give the program some arguments:

$ ./cmdline -s 2GiB -r 42 /dev/null
Option -s, --size set to 2147483648.
Option -r, --rounds N set to 42.
Parameter filename set to "/dev/null".
Command line parsed okay.
Parameters:
  filename        (string)            "/dev/null"
Options:
  -r, --rounds N  (unsigned integer)  42
  -s, --size      (bytes)             2147483648

The output shows pretty much what happens. The command line parser is by default in a verbose mode outputting all arguments and values parsed. The debug summary shows to have values the corresponding variables were set.

One feature worth naming is that the parser also supports lists of strings, i.e. std::vector<std::string> via cmdline_parser::add_param_stringlist() and similar.