From 1a59e2b190a9d05e34914041e855d2a35cbc9509 Mon Sep 17 00:00:00 2001 From: Ivar Fatland Date: Sat, 13 Dec 2025 16:30:27 +0100 Subject: [PATCH] file io --- cig.h | 5 +++++ file_io.c | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 file_io.c diff --git a/cig.h b/cig.h index edbbcab..a7d9611 100644 --- a/cig.h +++ b/cig.h @@ -339,6 +339,10 @@ void sb_add_substring(string_builder_t *this, const char *string, size_t substri const char *sb_build_and_clear(string_builder_t *this, allocator_t output_allocator); void sb_fprint_and_clear(string_builder_t *this, FILE *dest); +// file_io ///////////////////////////////////////////////////////////////////// +char *read_entire_file(const char *path, allocator_t allocator); +char **read_all_file_lines(const char *path, allocator_t allocator); + #ifdef CIG_IMPL void *allocator_alloc_func(allocator_t this, size_t bytes, const char *file, int line) { @@ -369,6 +373,7 @@ void allocator_reset(allocator_t this) { #include "cli.c" #include "scanner.c" #include "string_builder.c" +#include "file_io.c" #endif // CIG_IMPL diff --git a/file_io.c b/file_io.c new file mode 100644 index 0000000..de2d1a9 --- /dev/null +++ b/file_io.c @@ -0,0 +1,37 @@ +#include "cig.h" +#include + +char *read_entire_file(const char *path, allocator_t allocator) { + FILE *fp = fopen(path, "rb"); + assert(fp != NULL); + fseek(fp, 0, SEEK_END); + long size = ftell(fp); + rewind(fp); + char *buf = allocator_alloc(allocator, size+1); + assert(buf != NULL); + size_t read = fread(buf, 1, size, fp); + assert(read == (size_t)size); + fclose(fp); + buf[size] = '\0'; + return buf; +} + +// Returns dynamic array, of fixed char strings. +char **read_all_file_lines(const char *path, allocator_t allocator) { + char *contents = read_entire_file(path, allocator); + char **lines = make_arr(allocator, char*); + arr_append(lines, contents); + bool just_split = false; + for (char *c = contents; (*c)!='\0'; c++) { + if ((*c) == '\n') { + *c = '\0'; + just_split = true; + continue; + } + if (just_split) { + just_split = false; + arr_append(lines, c); + } + } + return lines; +}