From b23a3ab831f91553d34a48f51370ed9525de07ac Mon Sep 17 00:00:00 2001 From: zlago Date: Tue, 24 Sep 2024 20:54:48 +0200 Subject: initial commit --- src/util.c | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/util.c (limited to 'src/util.c') diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..fc20e94 --- /dev/null +++ b/src/util.c @@ -0,0 +1,66 @@ +#include // FILE * +#include // ESPIPE +#include +#include +#include // true/false + +#include "util.h" + +void *util_loadFile(FILE *const restrict file, size_t *const restrict outsize) { // open and fully load a file + if (ftell(file) == -1L) { + if (errno != ESPIPE) { + // perror("ftell"); + return NULL; + } + fputs("opening pipes isnt supported yet\n", stderr); + return NULL; + } else { + if (fseek(file, 0, SEEK_END)) { + // perror("fseek"); + } + long ssize = ftell(file); + size_t size = (size_t) ssize; + if (ssize == -1L) { + // perror("ftell"); + return NULL; + } + rewind(file); + void *buffer = malloc(size); + if (buffer == NULL) { + // perror("malloc"); + return NULL; + } + if (fread(buffer, 1, size, file) != size) { + if (ferror(file)) { + fputs("ferror set\n", stderr); // the internet was VERY helpful + } + // perror("fread"); + return NULL; + } + if (outsize != NULL) { + *outsize = size; + } + return buffer; + } +} + +#if defined(__unix__) || defined(__APPLE__) + #define DIR_SEPARATOR '/' // UNIX or OSX +#elif defined(_WIN32) + #define DIR_SEPARATOR '\\' // DOS +#endif + +char *util_executableRelativePath(char *path, char *execPath, size_t dirLength) { // allocated on the heap + dirLength = 0; + if (dirLength == 0) { + for (dirLength = strlen(execPath); dirLength > 0 && execPath[dirLength - 1] != DIR_SEPARATOR; dirLength--) + ; + } + + size_t fileLength = strlen(path); + char *filePath = malloc(dirLength + fileLength + 1); + filePath[dirLength + fileLength] = 0; + memcpy(filePath, execPath, dirLength); + memcpy(filePath + dirLength, path, fileLength); + return filePath; +} -- cgit 1.4.1-2-gfad0