summary refs log tree commit diff
path: root/src/util.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/util.c')
-rw-r--r--src/util.c66
1 files changed, 66 insertions, 0 deletions
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 <stdio.h> // FILE *
+#include <errno.h> // ESPIPE
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h> // 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;
+}