From bc415772486c087abd9cac9b9f2dc2b5dd5e98db Mon Sep 17 00:00:00 2001 From: Timerix Date: Tue, 18 Nov 2025 14:18:09 +0500 Subject: [PATCH] file_readWhole --- include/tlibc/filesystem.h | 4 ++++ src/filesystem/file.c | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/include/tlibc/filesystem.h b/include/tlibc/filesystem.h index 5c0a00c..14de757 100644 --- a/include/tlibc/filesystem.h +++ b/include/tlibc/filesystem.h @@ -130,6 +130,10 @@ static inline Result(void) file_readBytesArrayExactly(FILE* f, Array(u8) dst){ return file_readStructsExactly(f, dst.data, 1, dst.size); } +/// @brief allocates array of size equal `file_getSize()` and reads whole file +/// @param out_buf output array allocated on heap +Result(void) file_readWhole(FILE* f, Array(u8)* out_buf); + ////////////////////////////////////////////////////////////////////////////// // DIRECTORY // ////////////////////////////////////////////////////////////////////////////// diff --git a/src/filesystem/file.c b/src/filesystem/file.c index 4b52597..75b70f4 100644 --- a/src/filesystem/file.c +++ b/src/filesystem/file.c @@ -124,3 +124,17 @@ Result(void) file_readStructsExactly(FILE* f, void* dst, u64 struct_size, u64 ex } return RESULT_VOID; } + +Result(void) file_readWhole(FILE* f, Array(u8)* out_buf){ + Deferral(1); + bool success = false; + + try(i64 f_size, i, file_getSize(f)); + Array(u8) buf = Array_alloc(u8, f_size); + Defer(if(!success) free(buf.data)); + try_void(file_readBytesArray(f, buf)); + + *out_buf = buf; + success = true; + Return RESULT_VOID; +}