aboutsummaryrefslogtreecommitdiff
path: root/src/FileUtil.cpp
blob: 53687dd0f7569adf1988f5291eb17668b317f561 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "../include/FileUtil.hpp"
#include "../include/env.hpp"
#include <cstdio>

using namespace std;

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;
            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 };
    }
}