From: Michael Tremer Date: Mon, 6 Oct 2025 14:28:01 +0000 (+0000) Subject: util: Add a helper function to iterate through file handles X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=c0d468e53881051bd7ba08bccd7c92d8514b62cb;p=telemetry.git util: Add a helper function to iterate through file handles Signed-off-by: Michael Tremer --- diff --git a/src/daemon/util.c b/src/daemon/util.c index 45ae46f..bc9dc03 100644 --- a/src/daemon/util.c +++ b/src/daemon/util.c @@ -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; +} diff --git a/src/daemon/util.h b/src/daemon/util.h index 143e8b2..c50d507 100644 --- a/src/daemon/util.h +++ b/src/daemon/util.h @@ -22,6 +22,7 @@ #define COLLECTY_UTIL_H #include +#include #include // 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 */