-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIniFile.cpp
More file actions
111 lines (95 loc) · 2.08 KB
/
IniFile.cpp
File metadata and controls
111 lines (95 loc) · 2.08 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
109
110
111
#include "IniFile.h"
struct NotSpace
{
bool operator()(const char& ch) { return ch != ' ' && ch != '\t' && ch != '\r'; }
};
void StrTrim(string& str)
{
str.erase(str.begin(), std::find_if(str.begin(), str.end(), NotSpace()));
str.erase(std::find_if(str.rbegin(), str.rend(), NotSpace()).base(), str.end());
}
using namespace std;
IniFile::IniFile()
{
}
IniFile::~IniFile()
{
}
bool IniFile::Load(const char* fname)
{
ifstream in(fname);
if (!in)
return false;
string line;
string section("");
while (getline(in, line))
{
string str( line.begin(), find(line.begin(), line.end(), '#'));
StrTrim(str);
if (str.empty())
continue;
if (str[0] == '[')
{
auto it = find(str.begin(), str.end(), ']');
if (it != str.end())
{
section.assign(str.begin() + 1, it);
cout << '[' << section << ']' << endl;
}
continue;
}
string::iterator it = find(str.begin(), str.end(), '=');
if (it == str.end())
continue;
string key(str.begin(), it);
string val(++it, str.end());
StrTrim(key);
StrTrim(val);
if (!key.empty())
{
cout << section << '.' << key << '=' << val << endl;
m_iniMap[section].insert( make_pair(key, val) );
}
}
return true;
}
string IniFile::GetSetting(const char* sec, const char* key, const char* def_val)
{
auto it = m_iniMap.find(sec);
if (it != m_iniMap.end())
{
auto kv = it->second.find(key);
if (kv != it->second.end())
return kv->second;
}
return string(def_val);
}
bool IniFile::SetSetting(const char* sec, const char* key, const char* val)
{
auto it = m_iniMap.find(sec);
if (it != m_iniMap.end())
{
auto kv = it->second.find(key);
if (kv != it->second.end())
{
kv->second = val;
return true;
}
}
return false;
}
bool IniFile::Save(const char* fname)
{
ofstream out(fname);
if (!out)
return false;
for (auto& sm : m_iniMap)
{
out << '[' << sm.first << ']' << std::endl;
for (auto& kv : sm.second)
{
cout << kv.first << '=' << kv.second << std::endl;
}
}
return true;
}