diff options
Diffstat (limited to 'src/File.cpp')
-rw-r--r-- | src/File.cpp | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/File.cpp b/src/File.cpp new file mode 100644 index 0000000..b41d0ca --- /dev/null +++ b/src/File.cpp @@ -0,0 +1,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; + } +}
\ No newline at end of file |