65 lines
1.3 KiB
C++
65 lines
1.3 KiB
C++
//
|
|
// Created by quentin on 8/4/22.
|
|
//
|
|
|
|
|
|
#include "data.h"
|
|
|
|
#include <utility>
|
|
#include <fstream>
|
|
#include <vector>
|
|
#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);
|
|
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());
|
|
chkExistIfs.close();
|
|
}
|
|
else {
|
|
// File doesnt exist we need to create one
|
|
// This is the job of the derives constructor.
|
|
chkExistIfs.close();
|
|
};
|
|
}
|
|
|
|
template<class T>
|
|
std::string Data<T>::getFilePath() {
|
|
return fileName;
|
|
}
|
|
|
|
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() {
|
|
if (flush) {
|
|
flushToFile();
|
|
}
|
|
}
|
|
|
|
template<class T>
|
|
void Data<T>::deleteObject() {
|
|
remove(getFilePath().c_str());
|
|
flush = false;
|
|
}
|