1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
#include <cstdlib>
#define _GNU_SOURCE
#include <getopt.h>
#include "commandline.h"
Commandline::~Commandline (void)
{
std::map<std::string, Option *>::iterator i;
for (i = OptionsByName.begin (); i != OptionsByName.end (); i++)
delete i->second;
}
Commandline::Option &
Commandline::option (const std::string &n)
{
return *OptionsByName[n];
}
void
Commandline::AddOption (Option *op)
{
OptionsByName[op->name] = op;
OptionsBySop [op->shortop] = op;
}
void
Commandline::parse (int argc, char *argv[])
{
struct option *lopts = new struct option[OptionsByName.size ()];
std::string sopts;
std::map<std::string, Option *>::iterator i;
int c, j, option_index;
for (i = OptionsByName.begin (), j = 0; i != OptionsByName.end (); i++, j++) {
lopts[j].name = i->second->name.c_str ();
lopts[j].has_arg = i->second->argument;
lopts[j].flag = 0;
lopts[j].val = i->second->shortop;
if (i->second->shortop) {
sopts += i->second->shortop;
if (i->second->argument)
sopts += ':';
}
}
while ((c = getopt_long (argc, argv, sopts.c_str (), lopts, &option_index)) != -1) {
if (c != '?') {
Option *o = c ? OptionsBySop[c] : OptionsByName[lopts[option_index].name];
o->value = o->argument ? optarg : "true";
}
}
delete [] lopts;
}
void
Commandline::dump (std::ostream &dst) const
{
using namespace std;
map<string, Option *>::const_iterator i;
for (i = OptionsByName.begin (); i != OptionsByName.end (); i++) {
dst << "option \"" << i->second->name << "\" has value \"" << i->second->value << "\"" << endl;
}
}
std::ostream &
operator<< (std::ostream &dst, const Commandline &cmdline)
{
cmdline.dump (dst);
return dst;
}
std::ostream &
operator<< (std::ostream &dst, const Commandline *cmdline)
{
cmdline->dump (dst);
return dst;
}
Commandline::Option::Option (const char *n, char sop, const char *defval):
name (n),
shortop (sop),
argument (defval != 0),
value (argument ? defval : "false")
{
}
Commandline::Option::~Option (void)
{
}
Commandline::Option::operator bool ()
{
return ((value == "true") || (value == "1"));
}
Commandline::Option::operator int ()
{
const char *startptr = value.c_str ();
char *endptr;
long int result = std::strtol (startptr, &endptr, 0);
if (startptr == endptr)
throw InvalidArg (startptr);
return result;
}
Commandline::Option::operator double ()
{
const char *startptr = value.c_str ();
char *endptr;
double result = std::strtod (startptr, &endptr);
if (startptr == endptr)
throw InvalidArg (startptr);
return result;
}
Commandline::Option::operator std::string ()
{
return value;
}
|