This repository has been archived on 2020-05-16. You can view files and clone it, but cannot push or open issues or pull requests.
xdgjson/src/xdgjson.cpp

84 lines
1.4 KiB
C++

/* Public Domain / CC-0
* Author: tastytea <tastytea@tastytea.de>
*/
#if __cplusplus >= 201703L
#include <filesystem>
#else
#include <experimental/filesystem>
#endif
#include <fstream>
#include <sstream>
#include <basedir.h>
#include "xdgjson.hpp"
#if __cplusplus >= 201703L
namespace fs = std::filesystem;
#else
namespace fs = std::experimental::filesystem;
#endif
xdgjson::xdgjson(const string &filename, const string &subdir)
: _json()
{
xdgHandle xdg;
xdgInitHandle(&xdg);
_filepath = xdgConfigHome(&xdg);
xdgWipeHandle(&xdg);
if (!subdir.empty())
{
_filepath += '/' + subdir;
if (!fs::exists(_filepath))
{
fs::create_directory(_filepath);
}
}
_filepath += '/' + filename;
}
const bool xdgjson::read()
{
std::ifstream file(_filepath);
if (file.is_open())
{
std::stringstream config;
config << file.rdbuf();
file.close();
config >> _json;
return true;
}
else
{
return false;
}
}
const bool xdgjson::write()
{
std::ofstream file(_filepath);
if (file.is_open())
{
const string config = _json.toStyledString();
file.write(config.c_str(), config.length());
file.close();
return true;
}
else
{
return false;
}
}
Json::Value &xdgjson::get_json()
{
return _json;
}
const string xdgjson::get_filepath() const
{
return _filepath;
}