From d390f8ef2dc0cd041914d3c2fd3e1081605cbfc8 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Mon, 25 Jan 2016 22:42:36 +0100 Subject: util: introduce fputs_with_space() and make use of it at various places The call combines outputing a string with prefixing it with a space, optionally. This is useful to shorten the logic for outputing lists of strings, that are space separated. --- src/basic/fileio.c | 29 +++++++++++++++++++++++++++++ src/basic/fileio.h | 2 ++ src/basic/strv.c | 15 ++------------- 3 files changed, 33 insertions(+), 13 deletions(-) (limited to 'src/basic') diff --git a/src/basic/fileio.c b/src/basic/fileio.c index 5ed5460904..3ff70310e1 100644 --- a/src/basic/fileio.c +++ b/src/basic/fileio.c @@ -1251,3 +1251,32 @@ int read_timestamp_file(const char *fn, usec_t *ret) { *ret = (usec_t) t; return 0; } + +int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) { + int r; + + assert(s); + + /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter + * when specified shall initially point to a boolean variable initialized to false. It is set to true after the + * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each + * element, but not before the first one. */ + + if (!f) + f = stdout; + + if (space) { + if (!separator) + separator = " "; + + if (*space) { + r = fputs(separator, f); + if (r < 0) + return r; + } + + *space = true; + } + + return fputs(s, f); +} diff --git a/src/basic/fileio.h b/src/basic/fileio.h index 95e8698941..9e09574133 100644 --- a/src/basic/fileio.h +++ b/src/basic/fileio.h @@ -82,3 +82,5 @@ int tempfn_random_child(const char *p, const char *extra, char **ret); int write_timestamp_file_atomic(const char *fn, usec_t n); int read_timestamp_file(const char *fn, usec_t *ret); + +int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space); diff --git a/src/basic/strv.c b/src/basic/strv.c index dc5bafcf24..5532c53ad1 100644 --- a/src/basic/strv.c +++ b/src/basic/strv.c @@ -29,6 +29,7 @@ #include "alloc-util.h" #include "escape.h" #include "extract-word.h" +#include "fileio.h" #include "string-util.h" #include "strv.h" #include "util.h" @@ -879,25 +880,13 @@ int fputstrv(FILE *f, char **l, const char *separator, bool *space) { /* Like fputs(), but for strv, and with a less stupid argument order */ - if (!f) - f = stdout; - if (!separator) - separator = " "; if (!space) space = &b; STRV_FOREACH(s, l) { - if (*space) { - r = fputs(separator, f); - if (r < 0) - return r; - } - - r = fputs(*s, f); + r = fputs_with_space(f, *s, separator, space); if (r < 0) return r; - - *space = true; } return 0; -- cgit v1.2.3-54-g00ecf