summaryrefslogtreecommitdiff
path: root/src/util/file.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/util/file.c')
-rw-r--r--src/util/file.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/util/file.c b/src/util/file.c
new file mode 100644
index 0000000..38eb9ba
--- /dev/null
+++ b/src/util/file.c
@@ -0,0 +1,39 @@
+#include <string.h>
+#include "file.h"
+
+FILE *file_open(str s_path, const char *mode)
+{
+ NULTERM(s_path, path)
+ return fopen(path, mode);
+}
+
+static bool file_size(FILE *file, size_t *size)
+{
+ if (fseek(file, 0, SEEK_END) == -1)
+ return false;
+ long end = ftell(file);
+ fseek(file, 0, SEEK_SET);
+ if (end == -1)
+ return false;
+ *size = end;
+ return true;
+}
+
+str file_read(FILE *file)
+{
+ size_t size;
+ if (file_size(file, &size)) {
+ str s;
+ array_alloc(&s, size);
+ s.len = fread(s.ptr, 1, size, file);
+ return s;
+ } else {
+ strbuf buf = {};
+ size_t n_read;
+ do {
+ arraybuf_grow(&buf, BUFSIZ);
+ buf.len += (n_read = fread(buf.ptr+buf.len, 1, BUFSIZ, file));
+ } while (n_read == BUFSIZ);
+ return (str) arraybuf_cast(buf);
+ }
+}