-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConfigFile.cpp
84 lines (77 loc) · 1.93 KB
/
ConfigFile.cpp
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
/*
NAME
ConfigFile.cpp - Body file of the ConfigFile class.
DESCRIPTION
Simplify read content from configuration file.
读取配置文件信息
*/
#include "ConfigFile.hpp"
#include "Symbol.hpp"
#include "Utils.hpp"
#include <fstream>
// 构造函数
ConfigFile::ConfigFile(const std::string& filename)
{
std::ifstream file(filename.c_str());
std::string line;
std::string name;
std::string value;
std::string section;
std::string::size_type pos_equal;
line.reserve(LINE_SIZE);
while(getline(file, line)) {
// 空行
if(!line.size()) {
continue;
}
// 注释行
if(C_POUND == line[0] || C_SEMICOLON == line[0]) {
continue;
}
// 块区
if(C_L_BRACKET == line[0]) {
std::string::size_type pos = line.find(C_R_BRACKET);
if(std::string::npos != pos) {
section = trim(line.substr(1, pos - 1));
_sections.push_back(section);
_content[section] = "";
}
continue;
}
// 配置内容行
pos_equal = line.find(C_EQUAL);
if(std::string::npos != pos_equal) {
name = trim(line.substr(0, pos_equal));
value = trim(line.substr(pos_equal + 1));
_content[section + C_SLASH + name] = value;
}
}
file.close();
}
// 获取配置信息
const std::string& ConfigFile::value(const std::string& section, const std::string& entry)
{
std::map<std::string, std::string>::const_iterator ci = _content.find(section + C_SLASH + entry);
if(_content.end() == ci) {
throw "Section or entry does not exist.";
}
return ci->second;
}
// 判断指定的区块是否存在
bool ConfigFile::has_section(const std::string& section)
{
std::map<std::string, std::string>::const_iterator ci = _content.find(section);
if(_content.end() == ci) {
return false;
}
return true;
}
// 获取所有的块列表
std::list<std::string>* ConfigFile::get_sections()
{
return &_sections;
}
// 构造函数
ConfigFile::ConfigFile()
{
}