From 83091ac707f3e6a1e15df7ef13e61b97831e20ce Mon Sep 17 00:00:00 2001 From: Timerix Date: Wed, 26 Nov 2025 23:52:18 +0500 Subject: [PATCH] added file_readWholeText --- include/tlibc/filesystem.h | 6 +++++- src/filesystem/file.c | 22 ++++++++++++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/include/tlibc/filesystem.h b/include/tlibc/filesystem.h index 8447410..5e5c237 100644 --- a/include/tlibc/filesystem.h +++ b/include/tlibc/filesystem.h @@ -133,10 +133,14 @@ static inline Result(void) file_readBytesArrayExactly(FILE* f, Array(u8) dst){ return file_readStructsExactly(f, dst.data, 1, dst.len); } -/// @brief allocates array of size equal `file_getSize()` and reads whole file +/// @brief allocates buffer of size `file_getSize(f)` and reads whole file /// @param out_buf output array allocated on heap Result(void) file_readWhole(FILE* f, Array(u8)* out_buf); +/// @brief allocates buffer of size `file_getSize(f) + 1` and reads whole file +/// @param out_str output str allocated on heap, null-terminated +Result(void) file_readWholeText(FILE* f, str* out_str); + ////////////////////////////////////////////////////////////////////////////// // DIRECTORY // ////////////////////////////////////////////////////////////////////////////// diff --git a/src/filesystem/file.c b/src/filesystem/file.c index f100b7a..67b9ff2 100644 --- a/src/filesystem/file.c +++ b/src/filesystem/file.c @@ -142,10 +142,28 @@ Result(void) file_readWhole(FILE* f, Array(u8)* out_buf){ try(i64 f_size, i, file_getSize(f)); Array(u8) buf = Array_u8_alloc(f_size); - Defer(if(!success) free(buf.data)); - try_void(file_readBytesArray(f, buf)); + Defer(if(!success) Array_u8_destroy(&buf)); + + try_void(file_readBytesArrayExactly(f, buf)); *out_buf = buf; success = true; Return RESULT_VOID; } + +Result(void) file_readWholeText(FILE* f, str* out_str){ + Deferral(1); + bool success = false; + + try(i64 f_size, i, file_getSize(f)); + Array(u8) buf = Array_u8_alloc(f_size + 1); + Defer(if(!success) Array_u8_destroy(&buf)); + buf.len--; + + try_void(file_readBytesArrayExactly(f, buf)); + buf.data[buf.len] = '\0'; + + *out_str = Array_u8_castTo_str(buf, true); + success = true; + Return RESULT_VOID; +} \ No newline at end of file