Skip to content

Instantly share code, notes, and snippets.

@hsnks100
Created May 29, 2018 15:20
Show Gist options
  • Save hsnks100/45d0348f2b3a943d52651f379402f623 to your computer and use it in GitHub Desktop.
Save hsnks100/45d0348f2b3a943d52651f379402f623 to your computer and use it in GitHub Desktop.
SaveData can save json-file, edit json-file. It also need nlohmann/json(json.hpp)
#include <streambuf>
#include <iostream>
#include <sstream>
#include <fstream>
#include "json.hpp"
template <char const* m_fileName>
struct SaveData
{
using json = nlohmann::json;
json m_root;
static SaveData<m_fileName>* m_inst; // = nullptr;
static SaveData<m_fileName>* get() {
if(m_inst == nullptr) {
m_inst = new SaveData<m_fileName>();
}
return m_inst;
}
SaveData() {
}
const char *getFileName() const
{
return m_fileName;
}
int init() {
std::ifstream t(m_fileName);
std::string str;
if(!t.fail()) {
str = std::string((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
}
else {
str = "{}";
}
std::cout << str << std::endl;
if(str == "") {
}
else {
try {
m_root = json::parse(str);
}catch(json::parse_error pe) {
std::cerr << pe.what() << std::endl;
}
}
return 0;
}
enum SAVE{NO_SAVE, YES_SAVE};
int saveValue(const std::string& key, uint32_t value, SAVE save = YES_SAVE) { // , SAVE save = YES_SAVE) {
m_root[key] = value;
if(save == YES_SAVE) {
FILE* fp = fopen(getFileName(), "w");
fprintf(fp, m_root.dump().c_str(), m_root.dump().size());
fclose(fp);
}
else {
}
return 0;
}
int saveValue(const std::string& key, const std::string& value, SAVE save = YES_SAVE) {
m_root[key] = value;
if(save == YES_SAVE) {
FILE* fp = fopen(getFileName(), "w");
fprintf(fp, m_root.dump().c_str(), m_root.dump().size());
fclose(fp);
}
else {
}
return 0;
}
template<typename T>
auto getValue(const std::string& key) {
return m_root[key].get<T>();
}
};
template <char const* T> SaveData<T>* SaveData<T>::m_inst = nullptr;
char secretData[] = "secret.data";
char userData[] = "user.data";
using SD = SaveData<secretData>;
using US = SaveData<userData>;
int main(int /* argc */, char ** /* argv */) {
SD::m_inst = nullptr;
US::m_inst = nullptr;
SD::get()->init();
std::cout << SD::get()->m_root << std::endl;
US::get()->init();
std::cout << US::get()->m_root << std::endl;
SD::get()->saveValue("name", "ksoo", SD::NO_SAVE);
US::get()->saveValue("name", "kiho", US::YES_SAVE);
auto name1 = SD::get()->getValue<std::string>("name");
auto name2 = SD::get()->getValue<std::string>("name");
std::cout << name1 << std::endl;
std::cout << name2 << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment