【发布时间】:2018-03-22 14:44:48
【问题描述】:
我需要读取包含键值对的配置文件。 文件包含几个这样的字符串:
键1=值1
键2=值2
键N=值N
***//终止
class CFG
{
public:
static void Init(char* path_);
static string Param(string name_);
static string PrintAll();
private:
static void GetPathEXE(string path_);
static void ParseConfigFile();
static map<string, string> mapData;
};
void CFG::ParseConfigFile()
{
ifstream file;
file.open(Param("HomePath") + Param("Slash") + "ConfigMS.cfg");
if (file.is_open())
{
string file_line;
cmatch results;
regex reg3("(.*)=(.*)", std::regex_constants::ECMAScript);
std::cout<<"Parsing cfg file"<<endl;
while (getline(file, file_line) && (file_line.substr(0, 3) != "***"))
{
std::cout<<file_line<<endl;
std::regex_match(file_line.c_str(), results, reg3);
mapData.insert(std::pair<string,string>(results.str(1),results.str(2) ));
mapData[string(results.str(1))] =string( results.str(2));
std::cout<<"key: "<<results.str(1)<<" val: "<<results.str(2)<<endl;
}
//mapData["OuterIP"] = "10.77.1.68";
std::cout<<"Config loaded\n";
for (auto it : mapData)
{
std::cout<<it.first<<"="<<it.second<<endl;
}
if (Param("OuterIP") == "") mapData["Error"] = "IP for receiving messages not set in *.cfg file.\n";
//else if (data["sipName"] == "") error = "sipName for receiving messages not set in *.cfg file.\n";
}
else { mapData["Error"] = "Could not open *.cfg file. Check its existance or name. Name Must \"be ConfigMS.cfg\".\n"; }
if (Param("RTPPort") == Param("MGCPPort"))
{
mapData["Error"] = "RTP port is same as MGCP port. Please change one of them.\n";
}
if (Param("Error") != "")
{
cout << "\n" + Param("Error");
//system("pause");
exit(-1);
}
}
string CFG::Param(string name_)
{
return mapData[name_];
}
如果我依赖文件输入,我的地图中有 [OuterIP,10.77.1.68] 键值对,但函数 CFG::Param("OuterIP") 返回空字符串;而且我不知道如何解决这个问题;
【问题讨论】:
-
如果文件中没有
RTPPort和MGCPPort会发生什么?这行if (Param("RTPPort") == Param("MGCPPort"))返回true,因为两个空字符串相等。然后下一个if被执行,你的程序被exit函数中止。 -
我有 Init() 函数,它设置了一些默认值,这些行只是检查更改,可能会在配置文件解析后出现。