From 1c8bc7efeae2ad9311f23dd9f266cf0f77bcfc1e Mon Sep 17 00:00:00 2001 From: kingecg Date: Thu, 30 Mar 2023 23:44:03 +0800 Subject: [PATCH] add cmdline parser --- cmdlineparser.cpp | 62 +++++++++++++++++++++++++++++++++++++++++ include/cmdlineparser.h | 28 +++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 cmdlineparser.cpp create mode 100644 include/cmdlineparser.h diff --git a/cmdlineparser.cpp b/cmdlineparser.cpp new file mode 100644 index 0000000..ad2fb59 --- /dev/null +++ b/cmdlineparser.cpp @@ -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; +} diff --git a/include/cmdlineparser.h b/include/cmdlineparser.h new file mode 100644 index 0000000..cfec78d --- /dev/null +++ b/include/cmdlineparser.h @@ -0,0 +1,28 @@ +#ifndef CMDLINEPARSER_H +#define CMDLINEPARSER_H +#include +#include +#include +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 optMap; + map paraMap; + bool hasOptSet(string key); +}; + +#endif // CMDLINEPARSER_H