diff options
Diffstat (limited to 'src/Storage.cpp')
-rw-r--r-- | src/Storage.cpp | 39 |
1 files changed, 38 insertions, 1 deletions
diff --git a/src/Storage.cpp b/src/Storage.cpp index 588b085..0c3479a 100644 --- a/src/Storage.cpp +++ b/src/Storage.cpp @@ -2,6 +2,8 @@ #include "../include/env.hpp" #include <stdio.h> #include <assert.h> +#include <json/reader.h> +#include <json/writer.h> #if OS_FAMILY == OS_FAMILY_POSIX #include <pwd.h> @@ -122,7 +124,7 @@ namespace QuickMedia { int file_overwrite(const Path &path, const std::string &data) { FILE *file = fopen(path.data.c_str(), "wb"); if(!file) - return errno; + return -1; if(fwrite(data.data(), 1, data.size(), file) != data.size()) { fclose(file); @@ -154,4 +156,39 @@ namespace QuickMedia { break; } } + + bool read_file_as_json(const Path &filepath, Json::Value &result) { + std::string file_content; + if(file_get_content(filepath, file_content) != 0) { + fprintf(stderr, "Failed to get content of file: %s\n", filepath.data.c_str()); + return false; + } + + Json::CharReaderBuilder json_builder; + std::unique_ptr<Json::CharReader> json_reader(json_builder.newCharReader()); + std::string json_errors; + if(!json_reader->parse(file_content.data(), file_content.data() + file_content.size(), &result, &json_errors)) { + fprintf(stderr, "Failed to read file %s as json, error: %s\n", filepath.data.c_str(), json_errors.c_str()); + return false; + } + + return true; + } + + bool save_json_to_file_atomic(const Path &path, const Json::Value &json) { + Path tmp_path = path; + tmp_path.append(".tmp"); + + Json::StreamWriterBuilder json_builder; + if(file_overwrite(tmp_path, Json::writeString(json_builder, json)) != 0) + return false; + + // Rename is atomic under posix! + if(rename(tmp_path.data.c_str(), path.data.c_str()) != 0) { + perror("save_json_to_file_atomic rename"); + return false; + } + + return true; + } }
\ No newline at end of file |