C++读取配置文件

配置文件格式

 # nimei
host = 127.0.0.1
 port = 80

	key
	=123
mask = 255.255.255.0
# comment

C++代码

/**
 * @author xiaozi<245565986@qq.com>
 */
#include 
#include 
#include 
#include 

using namespace std;

string trim(const string& str);

int main(int agrc, char* argv[]) {
	const char* filename = "parse.conf";
	ifstream ifs(filename);

	string line = "";
	string key = "";
	string value = "";
	string::size_type pos = string::npos;

	map options;

	while(! ifs.eof()) {
		getline(ifs, line);

		line = trim(line);
		// 空行 和 注释行 和 不存在等号的行,跳过
		if(line.empty() || line.at(0) == '#') {
			continue;
		}

		if((pos = line.find('=')) == string::npos) {
			// cout << "语法错误" << endl;
			continue;
		}

		key = trim(line.substr(0, pos));
		value = trim(line.substr(pos + 1, line.size() - pos - 1));

		// key不为空的时候,留下该行数据
		if(! key.empty()) {
			options[key] = value;
		}
	}

	ifs.close();

	// 输出得到的数据
	map::iterator it;
	for(it = options.begin(); it != options.end(); it++) {
		cout << (*it).first << " => " << (*it).second << endl;
	}

	return 0;
}

string trim(const string& str) {
	if(str.empty()) {
		return str;
	}
	string::size_type pos = str.find_first_not_of(" \t\n\r\0\x0B");
	if(pos == string::npos) {
		return str;
	}
	string::size_type pos2 = str.find_last_not_of(" \t\n\r\0\x0B");
	return str.substr(pos, pos2 - pos + 1);
}

标签: none

添加新评论