From 784a667584a7def9ecf5775c5158908d8aa18407 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Sat, 10 Jun 2023 22:28:44 +0200 Subject: [PATCH] New helper function, fexistf(), made for the Infix project Signed-off-by: Joachim Wiberg --- src/fexist.c | 38 ++++++++++++++++++++++++++++++++++++++ src/lite.h | 1 + 2 files changed, 39 insertions(+) diff --git a/src/fexist.c b/src/fexist.c index c9eeb73..10b0a3a 100644 --- a/src/fexist.c +++ b/src/fexist.c @@ -29,8 +29,13 @@ */ #include +#include +#include +#include #include +#include "lite.h" + /** * Check if a file exists in the file system. * @param file File to look for, with full path. @@ -50,6 +55,39 @@ int fexist(const char *file) return 1; } +/** + * Like fexist() but with formatted string support + * @param fmt Formatted string to be composed into the file to look for. + * + * This is a wrapper for the fexist() function in lite.h, lessening the + * burden of having to compose the filename from parts in a seprate + * buffer. + * + * @returns @c TRUE(1) if the @a file exists, otherwise @c FALSE(0). + */ +int fexistf(const char *fmt, ...) +{ + va_list ap; + char *file; + int len; + + va_start(ap, fmt); + len = vsnprintf(NULL, 0, fmt, ap); + va_end(ap); + + file = alloca(len + 1); + if (!file) { + errno = ENOMEM; + return -1; + } + + va_start(ap, fmt); + vsnprintf(file, len + 1, fmt, ap); + va_end(ap); + + return fexist(file); +} + /** * Local Variables: * indent-tabs-mode: t diff --git a/src/lite.h b/src/lite.h index c8ddefd..bf50204 100644 --- a/src/lite.h +++ b/src/lite.h @@ -77,6 +77,7 @@ int erasef (const char *fmt, ...) __attribute__ ((format (printf, 1, 2)) char *fparseln (FILE *, size_t *, size_t *, const char[3], int); int fexist (const char *file); +int fexistf (const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));; int fisdir (const char *path); FILE *vfopenf (const char *mode, const char *fmt, va_list ap);