ConfigFile.cpp 1.8 KB
#include "ConfigFile.h"
#include <iostream>
#include <fstream>
using namespace std;

CConfigFile::CConfigFile()
{
}


CConfigFile::~CConfigFile()
{
}

std::string& trim(std::string &s)
{
	if (s.empty())
	{
		return s;
	}

	s.erase(0, s.find_first_not_of(" "));
	s.erase(s.find_last_not_of(" ") + 1);
	return s;
}

int CConfigFile::load(const char * filename)
{
	ifstream fin(filename);
	if (!fin) {
		return -1;
	}

	const int  LINE_LENGTH = 1000;
	char  str[LINE_LENGTH];
	while (fin.getline(str, LINE_LENGTH))
	{
		char * p = str;
		while (*p == 0x20 || *p == 0x9){
			p++;//bypass space and tab
		}
		if (*p == ';' || *p == '#'){
			continue;//bypass the comment line
		}

		std::string linestr = p;

		string::size_type position = linestr.find('=');
		if (position != linestr.npos) {
			string item = linestr.substr(0, position);
			int value_len = linestr.length() - position;
			if (value_len > 0) {
				string value = linestr.substr(position + 1, value_len);
				trim(item);
				trim(value);
				_configs[item] = value;
			}
		}
	}
	return 0;
}

std::string CConfigFile::lookup(const char * item)
{
	map<string, string>::iterator it = _configs.find(item);
	if (it != _configs.end()) {
		return (*it).second;
	}
	return "";
}

int CConfigFile::get_int(const char * item, int def)
{
	std::string value = lookup(item);
	if (value.length() > 0) {
		return atoi(value.c_str());
	}
	else
	{
		return def;
	}
}

float CConfigFile::get_float(const char * item, float def)
{
	std::string value = lookup(item);
	if (value.length() > 0) {
		return atof(value.c_str());
	}
	else
	{
		return def;
	}
}

std::string CConfigFile::get_string(const char * item, const char * def)
{
	std::string value = lookup(item);
	if (value.length() > 0) {
		return value;
	}
	else
	{
		return def;
	}
}