46 lines
1.0 KiB
C++
46 lines
1.0 KiB
C++
|
|
#include "json_config.h"
|
||
|
|
#include <fstream>
|
||
|
|
#include <filesystem>
|
||
|
|
|
||
|
|
namespace scar {
|
||
|
|
|
||
|
|
JsonConfig::JsonConfig(const std::string& file_path)
|
||
|
|
: file_path_(file_path), data_(nlohmann::json::object()) {}
|
||
|
|
|
||
|
|
bool JsonConfig::load() {
|
||
|
|
try {
|
||
|
|
std::ifstream file(file_path_);
|
||
|
|
if (!file.is_open()) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
file >> data_;
|
||
|
|
return true;
|
||
|
|
} catch (const std::exception&) {
|
||
|
|
data_ = nlohmann::json::object();
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
bool JsonConfig::save() const {
|
||
|
|
try {
|
||
|
|
// Ensure directory exists
|
||
|
|
std::filesystem::path path(file_path_);
|
||
|
|
if (path.has_parent_path()) {
|
||
|
|
std::filesystem::create_directories(path.parent_path());
|
||
|
|
}
|
||
|
|
|
||
|
|
std::ofstream file(file_path_);
|
||
|
|
if (!file.is_open()) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
file << data_.dump(2); // Pretty print with 2-space indent
|
||
|
|
return true;
|
||
|
|
} catch (const std::exception&) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace scar
|