aboutsummaryrefslogtreecommitdiff
path: root/src/FileUtil.cpp
blob: 59132dc81a277af27c2fa5d8503907e65d51fce1 (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
#include "../include/FileUtil.hpp"
#include <cstdio>

using namespace std;

namespace sibs
{
    FileType getFileType(const char *path)
    {
        tinydir_file file;
        if(tinydir_file_open(&file, path) == 0)
        {
            return file.is_dir ? FileType::DIRECTORY : FileType::REGULAR;
        }
        else
        {
            return FileType::FILE_NOT_FOUND;
        }
    }

    // TODO: Handle failure (directory doesn't exist, no permission etc)
    void walkDirFiles(const char *directory, FileWalkCallbackFunc callbackFunc)
    {
        tinydir_dir dir;
        tinydir_open(&dir, directory);

        while (dir.has_next)
        {
            tinydir_file file;
            tinydir_readfile(&dir, &file);
            if(file.is_reg)
                callbackFunc(&file);
            else if(_tinydir_strcmp(file.name, ".") != 0 && _tinydir_strcmp(file.name, "..") != 0)
                walkDirFiles(file.path, callbackFunc);
            tinydir_next(&dir);
        }

        tinydir_close(&dir);
    }

    Result<StringView> getFileContent(const char *filepath)
    {
        FILE *file = fopen(filepath, "rb");
        if(!file || errno != 0)
        {
            perror(filepath);
            return Result<StringView>::Err("Failed to open file");
        }

        fseek(file, 0, SEEK_END);
        size_t fileSize = ftell(file);
        fseek(file, 0, SEEK_SET);

        // TODO: Change this to string so it can be deallocated and use std::move to prevent copies
        char *result = (char*)malloc(fileSize + 1);
        if(!result)
        {
            std::string errMsg = "Failed to load file content from file: ";
            errMsg += filepath;
            throw std::runtime_error(errMsg);
        }
        result[fileSize] = '\0';
        fread(result, 1, fileSize, file);
        fclose(file);
        return Result<StringView>::Ok(StringView(result, fileSize));
    }

    bool fileOverwrite(const char *filepath, StringView data)
    {
        FILE *file = fopen(filepath, "wb");
        if(!file || errno != 0)
        {
            perror(filepath);
            return false;
        }
        fwrite(data.data, 1, data.size, file);
        fclose(file);
        return true;
    }
}