From 358db798825bf5d3504132ccbae790d4415af1be Mon Sep 17 00:00:00 2001 From: lisk77 Date: Thu, 28 Aug 2025 17:00:49 +0200 Subject: [PATCH] feat(utilities): added the get_file_content_with_size to properly handle binary files --- include/utilities.h | 1 + src/utilities.c | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/include/utilities.h b/include/utilities.h index 55fa6d6..0ff3a88 100644 --- a/include/utilities.h +++ b/include/utilities.h @@ -62,5 +62,6 @@ int cut_path(char*, char*); void combine_path(char*, char*); PathType get_path_type(const char*); char* get_file_content(char*); +char* get_file_content_with_size(char*, size_t*); #endif // UTILITIES_H diff --git a/src/utilities.c b/src/utilities.c index 7d84201..929f837 100644 --- a/src/utilities.c +++ b/src/utilities.c @@ -482,3 +482,24 @@ char* get_file_content(char* path) { return buf; } + +char* get_file_content_with_size(char* path, size_t* size) { + if (!path || !size) return NULL; + + FILE* file = fopen(path, "rb"); + if (!file) { perror("ERROR: could not open file in get_file_content_with_size!"); return NULL; } + if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return NULL; } + long file_size = ftell(file); + if (file_size < 0) { perror("ERROR: file size is negative in get_file_content_with_size!"); fclose(file); return NULL; } + if (fseek(file, 0, SEEK_SET) != 0) { fclose(file); return NULL; } + size_t n = (size_t)file_size; + + char* buf = (char*)malloc(n); + if (!buf) { fclose(file); return NULL; } + + size_t got = fread(buf, 1, n, file); + fclose(file); + + *size = got; + return buf; +}