From: Philippe Proulx Date: Tue, 9 Jul 2019 23:40:59 +0000 (-0400) Subject: Add bt_common_append_file_content_to_g_string() X-Git-Url: http://git.efficios.com/?p=babeltrace.git;a=commitdiff_plain;h=87c882849d73c8567c517d630d4fba6d48b555cb Add bt_common_append_file_content_to_g_string() This new function appends the content of a file (`FILE *`) to a `GString *` object. Signed-off-by: Philippe Proulx Change-Id: I8552873d0c26baafe994e0294c3609f2a221c6e0 Reviewed-on: https://review.lttng.org/c/babeltrace/+/1841 CI-Build: Simon Marchi Tested-by: jenkins --- diff --git a/src/common/common.c b/src/common/common.c index 8961475f..c8890cd2 100644 --- a/src/common/common.c +++ b/src/common/common.c @@ -1862,3 +1862,44 @@ int bt_common_g_string_append_printf(GString *str, const char *fmt, ...) } return print_len; } + +BT_HIDDEN +int bt_common_append_file_content_to_g_string(GString *str, FILE *fp) +{ + const size_t chunk_size = 4096; + int ret = 0; + char *buf; + size_t read_len; + gsize orig_len = str->len; + + BT_ASSERT(str); + BT_ASSERT(fp); + buf = g_malloc(chunk_size); + if (!buf) { + ret = -1; + goto end; + } + + while (true) { + if (ferror(fp)) { + ret = -1; + goto end; + } + + if (feof(fp)) { + break; + } + + read_len = fread(buf, 1, chunk_size, fp); + g_string_append_len(str, buf, read_len); + } + +end: + if (ret) { + /* Remove what was appended */ + g_string_truncate(str, orig_len); + } + + g_free(buf); + return ret; +} diff --git a/src/common/common.h b/src/common/common.h index 4a2362e3..1751f20b 100644 --- a/src/common/common.h +++ b/src/common/common.h @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -351,6 +352,15 @@ GString *bt_common_fold(const char *str, unsigned int total_length, BT_HIDDEN int bt_common_get_term_size(unsigned int *width, unsigned int *height); +/* + * Appends the textual content of `fp` to `str`, starting from its + * current position to the end of the file. + * + * This function does NOT rewind `fp` once it's done or on error. + */ +BT_HIDDEN +int bt_common_append_file_content_to_g_string(GString *str, FILE *fp); + /* * Wraps read() function to handle EINTR and partial reads. * On success, it returns `count` received as parameter. On error, it returns a