From: Michael Tremer Date: Wed, 13 Mar 2019 14:31:23 +0000 (+0000) Subject: libpakfire: util: Write function to read file into buffer X-Git-Tag: 0.9.28~1285^2~1072 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3bf7e142c3acb1486032787c8d5be449b5115adc;p=pakfire.git libpakfire: util: Write function to read file into buffer Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/include/pakfire/util.h b/src/libpakfire/include/pakfire/util.h index bc2a36aa3..e43510d73 100644 --- a/src/libpakfire/include/pakfire/util.h +++ b/src/libpakfire/include/pakfire/util.h @@ -22,6 +22,7 @@ #define PAKFIRE_UTIL_H #include +#include #include #include @@ -55,4 +56,6 @@ const char* pakfire_action_type_string(pakfire_action_type_t type); void init_libgcrypt(); +int pakfire_read_file_into_buffer(FILE* f, char** buffer, size_t* len); + #endif /* PAKFIRE_UTIL_H */ diff --git a/src/libpakfire/libpakfire.sym b/src/libpakfire/libpakfire.sym index 56a796ef8..471155082 100644 --- a/src/libpakfire/libpakfire.sym +++ b/src/libpakfire/libpakfire.sym @@ -336,6 +336,7 @@ global: pakfire_free; pakfire_get_errno; pakfire_path_join; + pakfire_read_file_into_buffer; local: *; diff --git a/src/libpakfire/util.c b/src/libpakfire/util.c index 50d252d17..092f11773 100644 --- a/src/libpakfire/util.c +++ b/src/libpakfire/util.c @@ -281,3 +281,40 @@ PAKFIRE_EXPORT const char* pakfire_action_type_string(pakfire_action_type_t type return NULL; } + +PAKFIRE_EXPORT int pakfire_read_file_into_buffer(FILE* f, char** buffer, size_t* len) { + if (!f) + return -EBADF; + + int r = fseek(f, 0, SEEK_END); + if (r) + return r; + + // Save length of file + *len = ftell(f); + + // Go back to the start + r = fseek(f, 0, SEEK_SET); + if (r) + return r; + + // Allocate buffer + *buffer = pakfire_malloc((sizeof(**buffer) * *len) + 1); + if (!*buffer) + return -ENOMEM; + + // Read content + fread(*buffer, *len, sizeof(**buffer), f); + + // Check we encountered any errors + r = ferror(f); + if (r) { + pakfire_free(*buffer); + return r; + } + + // Terminate the buffer + (*buffer)[*len] = '\0'; + + return 0; +}