aboutsummaryrefslogtreecommitdiff
path: root/src/FileUtils.cpp
blob: c4fb31864771b41b1f7cd4fd1164a3fd4f1aa6ed (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#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);
        }

        flockfile(file);
        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);
    }
    
    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);
    }
}