From 9c12de31ab03385cea3b7bc78582ef4fdb9b22cc Mon Sep 17 00:00:00 2001 From: nsfisis Date: Mon, 11 Aug 2025 15:19:18 +0900 Subject: feat: grow dynamic array --- io.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'io.c') diff --git a/io.c b/io.c index 6c92b20..ae02a0d 100644 --- a/io.c +++ b/io.c @@ -14,11 +14,24 @@ InFile* read_all(const char* filename) { if (!in) { return NULL; } - char* buf = calloc(1024 * 1024, sizeof(char)); + + size_t buf_size = 1024 * 10; + char* buf = calloc(buf_size, sizeof(char)); char* cur = buf; char* tmp = calloc(1024, sizeof(char)); + while (fgets(tmp, 1024, in)) { size_t len = strlen(tmp); + size_t used_size = cur - buf; + + if (buf_size <= used_size + len) { + size_t old_size = buf_size; + buf_size *= 2; + buf = realloc(buf, buf_size); + memset(buf + old_size, 0, buf_size - old_size); + cur = buf + used_size; + } + memcpy(cur, tmp, len); cur += len; } -- cgit v1.2.3-70-g09d2