您的位置:首页 > 编程语言 > C语言/C++

配置文件读取的简要C/C++代码

2017-06-19 23:56 411 查看
       经常涉及到配置文件, 经常要用, 来写个代码, 欢迎挑刺指正, 环境是linux/g++,  代码如下(配置文件的每行用"="分割):

#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: