From e9904604ce0199d696c4941dff4f5ad84d22355f Mon Sep 17 00:00:00 2001 From: LaG1924 <12997935+LaG1924@users.noreply.github.com> Date: Mon, 6 Aug 2018 20:04:50 +0500 Subject: Implemented Settings Manager --- src/Settings.cpp | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/Settings.cpp (limited to 'src/Settings.cpp') diff --git a/src/Settings.cpp b/src/Settings.cpp new file mode 100644 index 0000000..a585752 --- /dev/null +++ b/src/Settings.cpp @@ -0,0 +1,58 @@ +#include "Settings.hpp" + +#include +#include + +#include +#include + + +using json = nlohmann::json; + +std::map 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.insert(std::make_pair(it.key(), it->get())); + } + 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.insert(std::make_pair(key, defaultValue)); + it = values.find(key); + } + return it->second; +} + +void Settings::Write(const std::string &key, const std::string &value) { + values[key] = value; +} -- cgit v1.2.3