编程实例:
CUtil.h
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
std::string Ltrim(std::string& str)
{
if(str.empty())
{
return str;
}
return str.erase(0, str.find_first_not_of(" "));
}
std::string& Rtrim(std::string& str)
{
if(str.empty())
return str;
return str.erase(str.find_last_not_of(" ")+1);
}
std::string& Trim(std::string& str)
{
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ")+1);
return str;
}
class CConfig
{
public:
static std::string getValueString(std::string configFile, std::string section, std::string key, std::string defaultvalue);
static int getValueInt(std::string configFile, std::string section, std::string key, int defaultvalue);
static bool getValueBool(std::string configFile, std::string section, std::string key, bool defaultvalue);
};
std::string CConfig::getValueString(std::string configFile, std::string section, std::string key, std::string defaultvalue)
{
if(configFile.empty() || section.empty() || key.empty())
{
return defaultvalue;
}
std::fstream fin(configFile.c_str(), std::ios::in);
if(!fin)
{
return defaultvalue;
}
char buf[256];
bool isFind = false;
int index = 0;
std::string strline, value, cursecton, curkey;
while(!fin.eof())
{
fin.getline(buf, 256);
strline = buf;
Trim(strline);
switch(strline[0])
{
case '#':
case ';':
continue;
case '[':
index = strline.find_first_of(']');
if(index == std::string::npos)
continue;
cursecton = strline.substr(1, index -1);
Trim(cursecton);
break;
default:
if(cursecton != section)
continue;
index = strline.find_first_of('=');
curkey = strline.substr(0, index);
Trim(curkey);
if(curkey == key)
{
value = strline.substr(index+1);
Trim(value);
isFind = true;
}
}
}
fin.close();
if(isFind)
return value;
else
return defaultvalue;
}
int CConfig::getValueInt(std::string configFile, std::string section, std::string key, int defaultvalue)
{
char buf[256];
sprintf(buf, "%d", defaultvalue);
return atoi(getValueString(configFile, section, key, buf).c_str());
}
bool CConfig::getValueBool(std::string configFile, std::string section, std::string key, bool defaultvalue)
{
std::string res;
res = getValueString(configFile, section, key, defaultvalue?"true":"false");
if(res == "true")
return true;
else
return false;
}
TestUtil.cpp
#include "CUtil.h"
int main(int argc, char *argv[])
{
std::string str = " haha dd ";
std::cout << str.size() << "\n";
std::cout << Ltrim(str) << std::endl;
std::cout << str.size() << "\n";
std::cout << Rtrim(str) << std::endl;
std::cout << str.size() << "\n";
std::string v1 = CConfig::getValueString("./config", "test1", "key1", "sd");
int v2 = CConfig::getValueInt("./config", "test2", "key2", 9);
bool v3 = CConfig::getValueBool("./config", "test3","key3", true);
std::cout << v1 << " "<< v2 << " " << v3 << "\n";
return 0;
}
编译:
g++ -g -o testUtil CUtil.h TestUtil.cpp