aboutsummaryrefslogtreecommitdiff
path: root/src/system/fileutils.c
blob: 7bd68591efe23636ee75e7238cc26fcbde30b987 (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
#include "../../include/mgl/system/fileutils.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int mgl_load_file(const char *filepath, mgl_filedata *filedata) {
    int fd = open(filepath, O_RDONLY);
    if(fd == -1)
        return -1;

    struct stat st;
    if(fstat(fd, &st) == -1) {
        close(fd);
        return -1;
    }

    if(!S_ISREG(st.st_mode)) {
        close(fd);
        return -1;
    }

    unsigned char *data = malloc(st.st_size);
    if(!data) {
        close(fd);
        return -1;
    }

    if(read(fd, data, st.st_size) != st.st_size) {
        free(data);
        close(fd);
        return -1;
    }

    filedata->data = data;
    filedata->size = st.st_size;

    close(fd);
    return 0;
}

void mgl_filedata_free(mgl_filedata *self) {
    free(self->data);
    self->data = NULL;
    self->size = 0;
}