]> git.ipfire.org Git - pakfire.git/commitdiff
libpakfire: util: Write function to read file into buffer
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 13 Mar 2019 14:31:23 +0000 (14:31 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 13 Mar 2019 14:31:23 +0000 (14:31 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/include/pakfire/util.h
src/libpakfire/libpakfire.sym
src/libpakfire/util.c

index bc2a36aa317a1157aa9220be4bbb8c52c1e012b0..e43510d73e27d2ace7d9950013c56384dd1809bb 100644 (file)
@@ -22,6 +22,7 @@
 #define PAKFIRE_UTIL_H
 
 #include <stddef.h>
+#include <stdio.h>
 #include <sys/types.h>
 #include <time.h>
 
@@ -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 */
index 56a796ef87fe56439572db9ec876ff34ff32feaa..471155082333cf47170d0b9e2a93f81d83bc4281 100644 (file)
@@ -336,6 +336,7 @@ global:
        pakfire_free;
        pakfire_get_errno;
        pakfire_path_join;
+       pakfire_read_file_into_buffer;
 
 local:
        *;
index 50d252d176aae5cf040102737a747c5a81bbb611..092f117735560a7c4621917cec519bbff7af56a5 100644 (file)
@@ -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;
+}