add cmdline parser

This commit is contained in:
kingecg 2023-03-30 23:44:03 +08:00
parent ec3731b22d
commit 1c8bc7efea
2 changed files with 90 additions and 0 deletions

62
cmdlineparser.cpp Normal file
View File

@ -0,0 +1,62 @@
#include "cmdlineparser.h"
CmdLineParser::CmdLineParser()
{
}
void CmdLineParser::regOpt(OptDefine optdef)
{
optMap[optdef.shortName] = optdef;
}
string CmdLineParser::getOpt(string key)
{
if(!hasOptSet(key)){
return "";
}
return paraMap.at(key);
}
void CmdLineParser::parseArgs(int argc, char *argv[])
{
size_t s=optMap.size();
struct option *longOption = new option[s]();
int index=0;
string shortArgs;
for (auto i = optMap.begin(); i != optMap.end(); ++i){
struct option logopt={0};
OptDefine od = i->second;
logopt.name = od.name.c_str();
logopt.flag = NULL;
logopt.has_arg = od.needParam;
logopt.val = od.shortName;
if(logopt.val>=65 && logopt.val<=90){
// this is a short name
shortArgs.append(1,char(logopt.val));
if(logopt.has_arg != no_argument){
shortArgs.append(1,':');
}
}
index++;
}
int optIndex=0;
int opt;
while ((opt=getopt_long(argc, argv, shortArgs.c_str(), longOption, &optIndex))!=-1) {
OptDefine d = optMap.at(opt);
if(d.needParam == no_argument){
paraMap[d.name] = "true";
} else {
paraMap[d.name] = optarg;
}
}
}
bool CmdLineParser::hasOptSet(string key)
{
if(paraMap.find(key) == paraMap.end()){
return false;
}
return true;
}

28
include/cmdlineparser.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef CMDLINEPARSER_H
#define CMDLINEPARSER_H
#include <map>
#include <string>
#include <getopt.h>
using namespace std;
typedef struct {
string name;
int shortName;
int needParam;
string desc;
} OptDefine;
class CmdLineParser
{
public:
CmdLineParser();
void regOpt(OptDefine optdef);
string getOpt(string key);
void parseArgs(int argc, char *argv[]);
private:
map<int, OptDefine> optMap;
map<string, string> paraMap;
bool hasOptSet(string key);
};
#endif // CMDLINEPARSER_H