aboutsummaryrefslogtreecommitdiff
path: root/fileutils.c
diff options
context:
space:
mode:
Diffstat (limited to 'fileutils.c')
-rw-r--r--fileutils.c33
1 files changed, 33 insertions, 0 deletions
diff --git a/fileutils.c b/fileutils.c
index 233138c..137373b 100644
--- a/fileutils.c
+++ b/fileutils.c
@@ -1,6 +1,9 @@
#include "fileutils.h"
+#include "alloc.h"
+#include <stdio.h>
#include <stdlib.h>
+#include <errno.h>
#include <pwd.h>
#include <unistd.h>
@@ -12,3 +15,33 @@ const char* get_home_dir() {
}
return home_dir;
}
+
+int file_get_content(const char *filepath, char **data, long *size) {
+ int result = 0;
+ FILE *file = fopen(filepath, "rb");
+ if(!file) {
+ int err = -errno;
+ perror(filepath);
+ return err;
+ }
+
+ fseek(file, 0, SEEK_END);
+ *size = ftell(file);
+ if(*size == -1) {
+ fprintf(stderr, "Failed to tell the size of file %s, is it not a file?\n", filepath);
+ result = -1;
+ goto cleanup;
+ }
+ fseek(file, 0, SEEK_SET);
+
+ *data = alloc_or_crash(*size);
+ if((long)fread(*data, 1, *size, file) != *size) {
+ fprintf(stderr, "Failed to read all bytes in file %s\n", filepath);
+ result = -1;
+ goto cleanup;
+ }
+
+ cleanup:
+ fclose(file);
+ return result;
+}