]> git.ipfire.org Git - telemetry.git/commitdiff
util: Add a helper function to iterate through file handles
authorMichael Tremer <michael.tremer@ipfire.org>
Mon, 6 Oct 2025 14:28:01 +0000 (14:28 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Mon, 6 Oct 2025 14:28:01 +0000 (14:28 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/daemon/util.c
src/daemon/util.h

index 45ae46fd74a837bba19213fcfba7002864cb54c4..bc9dc031b44d134b533bfaa14b29a94bc1ea740f 100644 (file)
@@ -79,3 +79,45 @@ int collecty_format_title(char** title, const char* format, ...) {
 
        return 0;
 }
+
+int collecty_fwalk(FILE* f, collecty_fwalk_callback callback, void* data) {
+       char* line = NULL;
+       size_t length = 0;
+       size_t l = 0;
+       int r;
+
+       // Start at the beginning of the stream
+       r = fseek(f, 0L, SEEK_SET);
+       if (r < 0)
+               return -errno;
+
+       // Walk through all lines
+       for (;;) {
+               // Fetch the next line
+               r = getline(&line, &length, f);
+               if (r < 0) {
+                       // Reset r if have reached the end of the file
+                       if (feof(f))
+                               r = 0;
+
+                       break;
+               }
+
+               // Remove the trailing newline
+               collecty_string_rstrip(line);
+
+               // Determine the length of the line
+               l = strlen(line);
+
+               // Call the callback
+               r = callback(line, l, data);
+               if (r < 0)
+                       break;
+       }
+
+       // Cleanup
+       if (line)
+               free(line);
+
+       return r;
+}
index 143e8b2105652440d4c6bb38c23f6df18eef1610..c50d507c9a0d327f4b99a1441e359bc9b7d1615b 100644 (file)
@@ -22,6 +22,7 @@
 #define COLLECTY_UTIL_H
 
 #include <stdint.h>
+#include <stdio.h>
 #include <stdlib.h>
 
 // Preprocessor macro to make something a string
@@ -51,4 +52,8 @@ int collecty_file_read_uint64(const char* path, uint64_t* number);
 int collecty_format_title(char** title, const char* format, ...)
        __attribute__((format(printf, 2, 3)));
 
+typedef int (*collecty_fwalk_callback)(const char* line, const size_t length, void* data);
+
+int collecty_fwalk(FILE* f, collecty_fwalk_callback callback, void* data);
+
 #endif /* COLLECTY_UTIL_H */