经常涉及到配置文件, 经常要用, 来写个代码, 欢迎挑刺指正, 环境是linux/g++, 代码如下(配置文件的每行用"="分割):
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;
// 注意注意注意,后来我发现这个函数有坑,请参考:https://blog.csdn.net/stpeace/article/details/73472576
void deleteAllMark(string &s, const string &mark)
{
unsigned int nMarkSize = mark.size();
while(1)
{
unsigned int pos = s.find(mark);
if(pos == string::npos)
{
return;
}
s.erase(pos, nMarkSize);
}
}
int getConfigInfoFromFile(const string &filename, map<string, string> &mapInfo)
{
ifstream in(filename.c_str());
string line;
if(in)
{
while (getline (in, line)) // line不包含'\n'
{
// 去掉注释
unsigned int pos = line.find("//");
if(pos != string::npos)
{
line.erase(pos, line.size() - pos);
}
deleteAllMark(line, " ");
deleteAllMark(line, "\t");
pos = line.find("=");
if(pos == string::npos)
{
continue;
}
string key = line.substr(0, pos);
string value = line.substr(pos, line.size() - pos);
value.erase(0, 1);
// 兼容Windows直接复制过来的文件(非常重要)
unsigned int nSize = value.size();
if(nSize > 0 && value[nSize - 1] == '\r')
{
value = value.substr(0, nSize - 1);
}
if(!key.empty() && !value.empty())
{
mapInfo[key] = value;
}
}
return 0;
}
return -1;
}
int main()
{
string filename = "test.cfg";
map<string, string> mapInfo;
int iRet = getConfigInfoFromFile(filename, mapInfo);
if(iRet != 0)
{
cout << "file error" << endl;
return -1;
}
for(map<string, string>::iterator it = mapInfo.begin(); it != mapInfo.end(); ++it)
{
cout << it->first << "=" << it->second << endl;
}
return 0;
}
验证OK.