aboutsummaryrefslogtreecommitdiff
path: root/src/io/file.c
diff options
context:
space:
mode:
authorhachem <im@hachem.wtf>2026-08-30 01:31:15 +0200
committerhachem <im@hachem.wtf>2026-08-30 01:31:15 +0200
commitd235876f94f84dca15520a20bb476b916b927afb (patch)
tree3f87c62a55e76f0ba55efcc3ccb867f161ad2aa0 /src/io/file.c
parent11d3e0294d6c4d657c45c6f8de23dd628b61680d (diff)
add: read files into memory
Diffstat (limited to 'src/io/file.c')
-rw-r--r--src/io/file.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/io/file.c b/src/io/file.c
new file mode 100644
index 0000000..8ce8eef
--- /dev/null
+++ b/src/io/file.c
@@ -0,0 +1,61 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "io/file.h"
+
+bool read_file(const char* path, struct File* out)
+{
+ FILE* stream = fopen(path, "rb");
+ if (stream == NULL)
+ {
+ fprintf(stderr, "error: could not open '%s'\n", path);
+ return false;
+ }
+
+ if (fseek(stream, 0, SEEK_END) != 0)
+ {
+ fprintf(stderr, "error: could not read '%s'\n", path);
+ fclose(stream);
+ return false;
+ }
+
+ long length = ftell(stream);
+ if (length < 0)
+ {
+ fprintf(stderr, "error: could not read '%s'\n", path);
+ fclose(stream);
+ return false;
+ }
+ rewind(stream);
+
+ size_t size = (size_t)length;
+ char* data = malloc(size + 1);
+ if (data == NULL)
+ {
+ fprintf(stderr, "error: out of memory reading '%s'\n", path);
+ fclose(stream);
+ return false;
+ }
+
+ if (fread(data, 1, size, stream) != size)
+ {
+ fprintf(stderr, "error: could not read '%s'\n", path);
+ free(data);
+ fclose(stream);
+ return false;
+ }
+
+ data[size] = '\0';
+ fclose(stream);
+
+ out->data = data;
+ out->size = size;
+ return true;
+}
+
+void free_file(struct File* file)
+{
+ free(file->data);
+ file->data = NULL;
+ file->size = 0;
+}