aboutsummaryrefslogtreecommitdiff
path: root/src/FileUtils.cpp
diff options
context:
space:
mode:
authorAleksi Lindeman <0xdec05eba@gmail.com>2018-04-14 19:45:15 +0200
committerAleksi Lindeman <0xdec05eba@gmail.com>2018-04-14 19:45:24 +0200
commit6e4d46f8cf911b82a10e8cd25b65fcc421bbc712 (patch)
tree3d6ee838990389d920df934e20aea1700052ce74 /src/FileUtils.cpp
parent9c22be3516d5067b98b06271e2f3545713ff6099 (diff)
Store database storage to files, also loading
Diffstat (limited to 'src/FileUtils.cpp')
-rw-r--r--src/FileUtils.cpp57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/FileUtils.cpp b/src/FileUtils.cpp
new file mode 100644
index 0000000..3a78a63
--- /dev/null
+++ b/src/FileUtils.cpp
@@ -0,0 +1,57 @@
+#include "../include/odhtdb/FileUtils.hpp"
+#include "../include/odhtdb/env.hpp"
+
+using namespace std;
+
+namespace odhtdb
+{
+ OwnedMemory 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);
+ }
+
+ fseek(file, 0, SEEK_END);
+ size_t fileSize = ftell(file);
+ fseek(file, 0, SEEK_SET);
+
+ char *result = new char[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);
+ }
+}