#include "../include/odhtdb/FileUtils.hpp" #include "../include/odhtdb/env.hpp" using namespace std; #ifdef __MINGW32__ #define flockfile(fp) #define funlockfile(fp) #endif namespace odhtdb { OwnedByteArray fileGetContent(const boost::filesystem::path &filepath) { #if OS_FAMILY == OS_FAMILY_POSIX FILE *file = fopen(filepath.string().c_str(), "rb"); #else FILE *file = _wfopen(filepath.wstring().c_str(), L"rb"); #endif if(!file) { int error = errno; string errMsg = "Failed to open file: "; errMsg += filepath.string(); errMsg += "; reason: "; errMsg += strerror(error); throw FileException(errMsg); } flockfile(file); fseek(file, 0, SEEK_END); size_t fileSize = ftell(file); fseek(file, 0, SEEK_SET); u8 *result = new u8[fileSize]; fread(result, 1, fileSize, file); fclose(file); return { result, fileSize }; } void fileAppend(const boost::filesystem::path &filepath, const DataView &data) { #if OS_FAMILY == OS_FAMILY_POSIX FILE *file = fopen(filepath.string().c_str(), "ab+"); #else FILE *file = _wfopen(filepath.wstring().c_str(), L"ab+"); #endif if(!file) { int error = errno; string errMsg = "Failed to append to file: "; errMsg += filepath.string(); errMsg += "; reason: "; errMsg += strerror(error); throw FileException(errMsg); } flockfile(file); setbuf(file, NULL); fwrite(data.data, 1, data.size, file); fclose(file); } void fileOverwrite(const boost::filesystem::path &filepath, const DataView &data) { #if OS_FAMILY == OS_FAMILY_POSIX FILE *file = fopen(filepath.string().c_str(), "wb+"); #else FILE *file = _wfopen(filepath.wstring().c_str(), L"wb+"); #endif if(!file) { int error = errno; string errMsg = "Failed to overwrite file: "; errMsg += filepath.string(); errMsg += "; reason: "; errMsg += strerror(error); throw FileException(errMsg); } flockfile(file); setbuf(file, NULL); fwrite(data.data, 1, data.size, file); fclose(file); } }