栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【C++ 】读取配置文件

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【C++ 】读取配置文件

 main函数:

#include 
#include "configfile.h"
using namespace std;

int main() {
	ConfigFile cfg("test.cfg");
	cout << "Dump:" << endl;
	cfg.dump();
	cout << endl;
	cout << cfg.getvalue("who") << endl;
	cout << cfg.getvalue("number") << endl;
	cout << cfg.getvalue("number") << endl;
	cout << cfg.getvalue("notThere") << endl;
	cout << cfg.getvalue("notThere", -1) << endl;
	cout << cfg.getvalueidx("array", 2, -1) << endl;
	getchar();
	return 0;
}

config.h

#ifndef CONFIGFILE_H
#define CONFIGFILE_H
#include 
#include 
#include 
#include 
#include 


class ConfigFile {
public:
ConfigFile(std::string filename);
ConfigFile();
bool load(std::string filename);

~ConfigFile();
void dump(void);

template < typename T>
T getvalue(std::string key) {
	std::string str = datamap[key];
	if (str=="") {
		std::cerr << "WARNING: '" << key <<"' was not defined in " << filename << "! Value is undefined!" << std::endl;
	}
	std::stringstream ss;
	ss << str;
	T value;
	ss >> value;
	return value;	
}

template < typename T>
T getvalue(std::string key, T defaultValue) {
	std::string str = datamap[key];
	if (str=="") {
		return defaultValue;
	}
	return getvalue(key);
}

template < typename T>
T getvalueidx(std::string key,int idx, T defaultValue) {
	std::stringstream ss;
	ss << idx;
		std::string query=key+std::string("[")+ss.str()+std::string("]");
	return getvalue(query,defaultValue);
}

template < typename T>
T getvalueidx(std::string key,int idx) {
	std::stringstream ss;
	ss << idx;
	std::string query=key+std::string("[")+ss.str()+std::string("]");
	return getvalue(query);
}

private:

std::map datamap;
std::string filename;
};

#endif

config.cpp

#include "configfile.h"
#include 

using namespace std;

void str2lower(string &str) {
	for(unsigned int i=0;ifilename=filename;
	fstream f;
	f.open(filename.c_str(),fstream::in);
	if (!f.is_open())	{
		return false;
	}
	string line;
	int lnr=-1;
	while (getline(f,line))	{
		lnr++;
		//Skip Comments and empty lines
		if (! line.length()) continue;
	    if (line[0] == '#') continue;
    	if (line[0] == ';') continue;

		int posTrenner=line.find('=');
		if (posTrenner==-1)
			posTrenner=line.find(' ');
		if (posTrenner==-1) {
			cerr << "WARNING: Statement '" << line << "' in file "<< filename << ":"<::iterator iter= datamap.begin(); iter!=datamap.end();iter++){
		cout << "key: '" << iter->first <<"' t value: '"<< iter->second <<"'"< 

参考:

benreh/configfile: A very simple reader for config files written in C++ (github.com)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968443.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号