-
Notifications
You must be signed in to change notification settings - Fork 0
/
nini.h
124 lines (99 loc) · 1.92 KB
/
nini.h
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
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <map>
#include <string>
#include <cstdio>
#include <cstdint>
namespace Ini
{
namespace Util
{
// https://stackoverflow.com/a/1431206/14976549
char* ltrim(char* s)
{
while(isspace(*s)) s++;
return s;
}
char* rtrim(char* s)
{
char* back = s + strlen(s);
while(isspace(*--back));
*(back+1) = '\0';
return s;
}
char* trim(char* s)
{
return rtrim(ltrim(s));
}
}
class Section
{
friend class File;
private:
std::map<std::string, std::string> entries;
public :
std::string& operator [] (const std::string& key)
{
return entries[key];
}
};
class File
{
private:
std::string fpath;
std::map<std::string, Section> sections;
public :
Section& operator [] (const std::string& section)
{
return sections[section];
}
bool load(const std::string& path)
{
Section* current_section;
FILE* fp = fopen(path.c_str(), "r");
if (!fp) return false;
char key[4096]{'\0'};
char val[4096]{'\0'};
char line[10000]{'\0'};
char title[4096]{'\0'};
using namespace Ini::Util;
while(fgets(line, sizeof(line), fp))
{
if (line[0] == ';' or line[0] == '#'); // ignore comments
else if (1 == sscanf(line, "[%[^]]]", title))
{
current_section = §ions[trim(title)];
}
else if (2 == sscanf(line, "%[^=]=%[^\n]", key, val))
{
(*current_section)[trim(key)] = trim(val);
}
}
std::fclose(fp); return true;
}
bool save(const std::string& path)
{
FILE* fp = fopen(path.c_str(), "w");
if (!fp) return false;
std::string line;
for (auto& [title, section] : sections)
{
line = "\n["+title+"]\n";
std::fprintf(fp, "%s\n", line.c_str());
for (auto& [key, value] : section.entries)
{
line = key+" = "+value;
std::fprintf(fp, "%s\n", line.c_str());
}
}
std::fclose(fp); return true;
}
File();
File(const std::string& path) : fpath(path)
{
load(fpath);
}
~File()
{
if (!fpath.empty()) save(fpath);
}
};
}