aboutsummaryrefslogtreecommitdiff
path: root/src/File.cpp
blob: b41d0ca9fdb2f755aabdd7c044d98b6d096e1f4f (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
#include "../include/File.hpp"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

namespace amalgine {
    char* file_get_content(const char *filepath, size_t *filesize) {
        struct stat file_stat;
        int fd = open(filepath, O_RDONLY);
        char *result = NULL;
        *filesize = 0;
        if(fd == -1) {
            perror(filepath);
            return NULL;
        }

        if(fstat(fd, &file_stat) == -1) {
            perror(filepath);
            goto cleanup;
        }

        if(!S_ISREG(file_stat.st_mode)) {
            fprintf(stderr, "Error: %s is not a file\n", filepath);
            goto cleanup;
        }

        *filesize = file_stat.st_size;
        result = (char*)malloc(*filesize + 1);
        if(!result) {
            *filesize = 0;
            fprintf(stderr, "Error: Failed to malloc %lu bytes from file %s\n", *filesize, filepath);
            goto cleanup;
        }

        result[*filesize] = '\0';
        if((size_t)read(fd, result, *filesize) != *filesize) {
            free(result);
            result = NULL;
            *filesize = 0;
            fprintf(stderr, "Error: Failed to read all data from file %s\n", filepath);
            goto cleanup;
        }

        cleanup:
        close(fd);
        return result;
    }
}