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

972 篇文章 329 订阅
166 篇文章 14 订阅

       经常涉及到配置文件, 经常要用, 来写个代码, 欢迎挑刺指正, 环境是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.

 

 

 

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值