budget/src/data/data.tpp

57 lines
1.2 KiB
C++
Raw Normal View History

//
// Created by quentin on 8/4/22.
//
#include "data.h"
#include <utility>
#include <fstream>
#include <vector>
2022-09-05 20:38:07 -05:00
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
template<class T>
Data<T>::Data(std::string file) : fileName(std::move(file)) {
// Create file if it doesnt exist
std::ifstream chkExistIfs(getFilePath(), std::ios::in | std::ios::binary | std::ios::ate);
2022-09-05 20:38:07 -05:00
if (chkExistIfs) {
// File exists, were not creating one
std::ifstream::pos_type fileSize = chkExistIfs.tellg();
chkExistIfs.seekg(0, std::ios::beg);
std::vector<char> bytes(fileSize);
chkExistIfs.read(bytes.data(), fileSize);
document.Parse(std::string(bytes.data(), fileSize).c_str());
2022-09-05 20:38:07 -05:00
chkExistIfs.close();
}
else {
// File doesnt exist we need to create one
// This is the job of the derives constructor.
2022-09-05 20:38:07 -05:00
chkExistIfs.close();
};
}
template<class T>
std::string Data<T>::getFilePath() {
return fileName;
}
2022-09-05 20:38:07 -05:00
template<class T>
void Data<T>::flushToFile() {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
document.Accept(writer);
std::ofstream file(getFilePath());
file << buffer.GetString();
file.close();
}
template<class T>
Data<T>::~Data() {
flushToFile();
}