【C++ 】读取配置文件

【C++ 】读取配置文件,第1张

 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)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1499158.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-25
下一篇 2022-06-25

发表评论

登录后才能评论

评论列表(0条)