From e5af28536bfb0f4c9131df56d2009ba5196f5e3a Mon Sep 17 00:00:00 2001 From: Lizzy Fleckenstein Date: Sun, 12 Apr 2026 20:57:06 +0200 Subject: init --- src/util/file.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/util/file.c (limited to 'src/util/file.c') 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 +#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); + } +} -- cgit v1.2.3