ConfigFile.cpp
1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "ConfigFile.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>
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;
}
}