-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnini.cpp
138 lines (109 loc) · 2.17 KB
/
nini.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
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#pragma once
// Licence : Apache 2.0
// Author : Tanishq-Banyal
// Source : github.com/Tanishq-Banyal/nini
// Changes : Made More QT Friendly (at performance cost)
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdint>
#include <QtCore/QString>
namespace Ini
{
namespace Util
{
char* ltrim(char* s)
{
while(std::isspace(*s)) s++;
return s;
}
char* rtrim(char* s)
{
char* back = s + std::strlen(s);
while(std::isspace(*--back));
*(back+1) = '\0';
return s;
}
char* trim(char* s)
{
return rtrim(ltrim(s));
}
}
class Section
{
friend class File;
private:
std::map<QString, QString> entries;
public :
QString& operator [] (const QString& key)
{
return entries[key];
}
};
class File
{
private:
QString fpath;
std::map<QString, Section> sections;
public :
Section& operator [] (const QString& section)
{
return sections[section];
}
bool load(const QString& path)
{
Section* current_section;
FILE* fp = fopen(path.toStdString().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 QString& path)
{
FILE* fp = fopen(path.toStdString().c_str(), "w");
if (!fp) return false;
QString line;
for (auto& [title, section] : sections)
{
line = "\n["+title+"]\n";
std::fprintf(fp, "%s\n", line.toStdString().c_str());
for (auto& [key, value] : section.entries)
{
line = key+" = "+value;
std::fprintf(fp, "%s\n", line.toStdString().c_str());
}
}
std::fclose(fp); return true;
}
void clear()
{
sections.clear();
}
File() = default;
File(const QString& path) : fpath(path)
{
load(fpath);
}
~File()
{
if (!fpath.isEmpty()) save(fpath);
}
};
}