blob: 5287556c22f0511d8c28597139517a18c3c1c3d9 (
plain) (
blame)
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
|
#include "Settings.hpp"
#include <fstream>
#include <map>
#include <nlohmann/json.hpp>
#include <easylogging++.h>
using json = nlohmann::json;
std::map<std::string, std::string> values;
const std::string saveFileName = "./settings.json";
void Settings::Load() {
std::ifstream stream(saveFileName);
if (!stream) {
LOG(ERROR) << "Loading settings failed: Can't open ifstream for " << saveFileName << ": " << strerror(errno);
return;
}
json j;
stream >> j;
for (json::iterator it = j.begin(); it != j.end(); ++it) {
values.try_emplace(it.key(), it->get<std::string>());
}
LOG(INFO) << "Loaded " << values.size() << " settings";
}
void Settings::Save() {
json j;
for (auto &it : values) {
j[it.first] = it.second;
}
std::string text = j.dump(4);
std::ofstream stream(saveFileName);
if (!stream) {
LOG(ERROR) << "Saving settings failed: Can't open ofstream for " << saveFileName << ": "<< strerror(errno);
return;
}
stream << text;
LOG(INFO) << "Saved " << values.size() << " settings";
}
std::string Settings::Read(const std::string &key, const std::string &defaultValue) {
auto it = values.find(key);
if (it == values.end()) {
values.try_emplace(key, defaultValue);
it = values.find(key);
}
return it->second;
}
void Settings::Write(const std::string &key, const std::string &value) {
values[key] = value;
}
|