diff options
author | dec05eba <dec05eba@protonmail.com> | 2018-10-29 21:49:54 +0100 |
---|---|---|
committer | dec05eba <dec05eba@protonmail.com> | 2018-10-29 21:52:12 +0100 |
commit | b1296f2c97c6fdc1c6a9922dc09c951b5cafdc12 (patch) | |
tree | 0986a2e3ab45f73c1f7219deef044b3d4ca94e89 /src/FileUtil.cpp |
Initial commit
Diffstat (limited to 'src/FileUtil.cpp')
-rw-r--r-- | src/FileUtil.cpp | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/FileUtil.cpp b/src/FileUtil.cpp new file mode 100644 index 0000000..08efd00 --- /dev/null +++ b/src/FileUtil.cpp @@ -0,0 +1,55 @@ +#include "../include/FileUtil.hpp" +#include "../include/env.hpp" +#include <stdio.h> + +namespace dchat +{ + StringView getFileContent(const boost::filesystem::path &filepath) + { +#if OS_FAMILY == OS_FAMILY_POSIX + FILE *file = fopen(filepath.c_str(), "rb"); +#else + FILE *file = _wfopen(filepath.c_str(), L"rb"); +#endif + if(!file) + { + int error = errno; + std::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 *fileData = new char[fileSize]; + fread(fileData, 1, fileSize, file); + fclose(file); + return { fileData, fileSize }; + } + + void fileReplace(const boost::filesystem::path &filepath, const StringView 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; + std::string errMsg = "Failed to replace file: "; + errMsg += filepath.string(); + errMsg += ", reason: "; + errMsg += strerror(error); + throw FileException(errMsg); + } + + setbuf(file, NULL); + fwrite(data.data, 1, data.size, file); + fclose(file); + } +} |