From: momoyon Date: Sun, 6 Apr 2025 15:30:13 +0000 (+0500) Subject: Change slurp_file() to return file_size instead of success. X-Git-Url: https://www.git.momoyon.org/?a=commitdiff_plain;h=1dfb6a79c6cfd0f196408587cea392c9f9b774b8;p=commonlib.git Change slurp_file() to return file_size instead of success. --- diff --git a/commonlib.h b/commonlib.h index 3eb80c8..ebef2ca 100644 --- a/commonlib.h +++ b/commonlib.h @@ -208,8 +208,8 @@ bool c_os_file_exists(cstr filename); // File // -// reads entire file and gives back the string holding the contents. (caller must be responsible for freeing the string!) -const char* c_slurp_file(const char* filename, bool* success); +// reads entire file and gives back the file content and filesize in bytes. (caller must be responsible for freeing the string!) +const char* c_slurp_file(const char* filename, int *file_size); void c_touch_file_if_doesnt_exist(cstr file); // @@ -334,7 +334,7 @@ bool c_os_file_exists(cstr filename) { result = ret_val;\ goto defer -const char *c_slurp_file(const char* filename, bool* success) { +const char *c_slurp_file(const char* filename, int *file_size) { FILE* f = fopen(filename, "rb"); char* result = NULL; @@ -355,6 +355,8 @@ const char *c_slurp_file(const char* filename, bool* success) { defer(NULL); } + *file_size = (int)fsize; + result = C_MALLOC(sizeof(char)*(fsize+1)); if (result == NULL){ @@ -377,7 +379,7 @@ const char *c_slurp_file(const char* filename, bool* success) { defer: if (f) fclose(f); - *success = result != NULL; + if (result == NULL) *file_size = -1; return result; } diff --git a/tests/.slurp_file.out.expected b/tests/.slurp_file.out.expected index 1483648..f2d6e97 100644 --- a/tests/.slurp_file.out.expected +++ b/tests/.slurp_file.out.expected @@ -1,15 +1,29 @@ [INFO] buff: '#define COMMONLIB_IMPLEMENTATION + #include "../commonlib.h" + + int main(void) { - bool success = false; - const char *buff = c_slurp_file(__FILE__, &success); + + int file_size = 0; + + const char *buff = c_slurp_file(__FILE__, &file_size); + - if (!success) { return 1; } - c_log_info("buff: '%s'", buff); + if (file_size < 0) { return 1; } + + + + c_log_info("buff: '%s' (%d bytes)", buff, file_size); + + // We don't care about leaking memory since we are just exiting right away! + return 0; + } -' + +' (375 bytes) diff --git a/tests/slurp_file.c b/tests/slurp_file.c index 50d4ae4..f5413ea 100644 --- a/tests/slurp_file.c +++ b/tests/slurp_file.c @@ -2,12 +2,12 @@ #include "../commonlib.h" int main(void) { - bool success = false; - const char *buff = c_slurp_file(__FILE__, &success); + int file_size = 0; + const char *buff = c_slurp_file(__FILE__, &file_size); - if (!success) { return 1; } + if (file_size < 0) { return 1; } - c_log_info("buff: '%s'", buff); + c_log_info("buff: '%s' (%d bytes)", buff, file_size); // We don't care about leaking memory since we are just exiting right away! return 0;