-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconfig-parser.cc
69 lines (58 loc) · 1.95 KB
/
config-parser.cc
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
#include "config-parser.h"
#include <cassert>
#include <fstream>
// Returns a new string that has all padding whitespace removed.
static string StripWhiteSpace(const string& s) {
size_t start_pos = 0;
size_t end_pos = s.length() - 1;
while (s[start_pos] == ' ' && start_pos < s.length()) {
++start_pos;
}
while (s[end_pos] == ' ' && end_pos >= 0) {
--end_pos;
}
assert(start_pos < end_pos);
return s.substr(start_pos, end_pos - start_pos + 1);
}
bool ConfigParser::ParseConfig(const string& file_path,
map<string, map<string, string> >* config) {
std::ifstream config_file(file_path.c_str());
if (!config_file.is_open()) {
fprintf(stderr, "Unable to open config file %s.\n", file_path.c_str());
return false;
}
string line;
map<string, string>* current_section = NULL;
while (!config_file.eof()) {
getline(config_file, line);
// Skip comment lines.
if (line.empty() || line[0] == '#') {
continue;
}
// Grab this section.
if (line[0] == '[' && line[line.length() - 1] == ']') {
current_section = &(*config)[line.substr(1, line.length() - 2)];
continue;
}
// If we get this far and we don't already have a section, bail out. This
// can occur when no section is provided initially.
if (current_section == NULL) {
fprintf(stderr, "No section at beginning of config file.\n");
return false;
}
// Parse the configuration param.
size_t equals_pos = line.find("=");
if (equals_pos == string::npos) {
// All configs must have an equals sign in them.
fprintf(stderr, "Unable to parse '%s'. Must have an = sign.\n",
line.c_str());
return false;
}
string key = StripWhiteSpace(line.substr(0, equals_pos));
string value = StripWhiteSpace(
line.substr(equals_pos + 1, line.size() - equals_pos - 1));
(*current_section)[key] = value;
}
config_file.close();
return true;
}