File: OptParser.cc

package info (click to toggle)
wbar 1.3.3%2Bdfsg2-1
  • links: PTS
  • area: main
  • in suites: squeeze, wheezy
  • size: 224 kB
  • ctags: 201
  • sloc: cpp: 1,307; sh: 102; makefile: 70
file content (53 lines) | stat: -rw-r--r-- 1,231 bytes parent folder | download
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
#include "OptParser.h"

using namespace std;

OptParser::OptParser() : optCount(0) {}

void OptParser::addOption(const char *name, bool hasArg, const char *defArg){
    if(optCount >= MAXOPTS)
	throw "Max numer of options reached";

    /* they will be harcoded strings so dont alloc them */
    longOption[optCount].name = name;
    longOption[optCount].has_arg = hasArg;
    longOption[optCount].flag = 0;
    longOption[optCount].val = 0;

    if(defArg)
	setOption[optCount].argument = defArg;
    setOption[optCount].isOptionSet = (hasArg && defArg != NULL)? 2:0;

    optCount++;
}

void OptParser::parse(int argc, char * const argv[]){
    int optIndex, c;

    while( (c=getopt_long_only(argc, argv, "h", longOption, &optIndex)) != -1 )
	if(c == 0){
	    setOption[optIndex].isOptionSet = 1;
	    if(optarg)
		setOption[optIndex].argument = optarg;
	}
}

int OptParser::isset(string name){

    for(int i=0; i<optCount; i++)
	if(longOption[i].name == name)
	    if(setOption[i].isOptionSet == 1)
		return 1;

    return 0;
}

string OptParser::getArg(string name){

    for(int i=0; i<optCount; i++)
	if(longOption[i].name == name)
	    if(setOption[i].isOptionSet != 0)
		return setOption[i].argument;

    return NULL;
}