From: Alejandro Colomar Date: Wed, 23 Jul 2025 12:19:52 +0000 (+0200) Subject: lib/io/fprintf.h: [v]fprintec(): Add functions X-Git-Tag: 4.20.0-rc3~30 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=b9bb887fbb72a24d85b6d19414d5e18e2205eca1;p=thirdparty%2Fshadow.git lib/io/fprintf.h: [v]fprintec(): Add functions These functions print a formatted string, followed by a colon and a space, followed by an error string produced by strerror($2). That is, the output is as follows: fmt: error message string For example, fprintec(stderr, ENOMEM, "foo(%d)", 42); prints foo(42): Cannot allocate memory These functions return the number of characters printed, or a negative value on error, like fprintf(3). Signed-off-by: Alejandro Colomar --- diff --git a/lib/Makefile.am b/lib/Makefile.am index 599cb0bbd..2995cca66 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -105,6 +105,8 @@ libshadow_la_SOURCES = \ idmapping.c \ io/fgets/fgets.c \ io/fgets/fgets.h \ + io/fprintf.c \ + io/fprintf.h \ io/syslog.c \ io/syslog.h \ isexpired.c \ diff --git a/lib/io/fprintf.c b/lib/io/fprintf.c new file mode 100644 index 000000000..452d8dd85 --- /dev/null +++ b/lib/io/fprintf.c @@ -0,0 +1,16 @@ +// SPDX-FileCopyrightText: 2025, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#include "config.h" + +#include "io/fprintf.h" + +#include +#include + + +extern inline int fprintec(FILE *restrict stream, int e, + const char *restrict fmt, ...); +extern inline int vfprintec(FILE *restrict stream, int e, + const char *restrict fmt, va_list ap); diff --git a/lib/io/fprintf.h b/lib/io/fprintf.h new file mode 100644 index 000000000..356d72151 --- /dev/null +++ b/lib/io/fprintf.h @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2025, Alejandro Colomar +// SPDX-License-Identifier: BSD-3-Clause + + +#ifndef SHADOW_INCLUDE_LIB_IO_FPRINTF_H_ +#define SHADOW_INCLUDE_LIB_IO_FPRINTF_H_ + + +#include "config.h" + +#include +#include +#include + +#include "attr.h" + + +format_attr(printf, 3, 4) +inline int fprintec(FILE *restrict stream, int e, + const char *restrict fmt, ...); +format_attr(printf, 3, 0) +inline int vfprintec(FILE *restrict stream, int e, + const char *restrict fmt, va_list ap); + + +// fprintec - FILE* print errno code +inline int +fprintec(FILE *restrict stream, int e, const char *restrict fmt, ...) +{ + int len; + va_list ap; + + va_start(ap, fmt); + len = vfprintec(stream, e, fmt, ap); + va_end(ap); + + return len; +} + + +// vfprintec - va_list FILE* print errno code +inline int +vfprintec(FILE *restrict stream, int e, const char *restrict fmt, va_list ap) +{ + int l1, l2, l3; + + l1 = vfprintf(stream, fmt, ap); + if (l1 < 0) + return l1; + + l2 = fprintf(stream, l1 ? ": " : ""); + if (l2 < 0) + return l2; + + l3 = fprintf(stream, "%s\n", strerror(e)); + if (l3 < 0) + return l3; + + return l1 + l2 + l3; +} + + +#endif // include guard