diff options
Diffstat (limited to 'src/system')
-rw-r--r-- | src/system/fileutils.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/system/fileutils.c b/src/system/fileutils.c new file mode 100644 index 0000000..7bd6859 --- /dev/null +++ b/src/system/fileutils.c @@ -0,0 +1,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; +} |