changeset 236:4896bb07a8db

core: add pprintf function
author David Demelier <markand@malikania.fr>
date Fri, 27 Nov 2020 13:31:16 +0100
parents fb304a94a05c
children 1bf5bd306bb0
files libcore/core/util.c libcore/core/util.h
diffstat 2 files changed, 29 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/libcore/core/util.c	Thu Nov 26 18:00:45 2020 +0100
+++ b/libcore/core/util.c	Fri Nov 27 13:31:16 2020 +0100
@@ -17,6 +17,7 @@
  */
 
 #include <assert.h>
+#include <limits.h>
 #include <stdlib.h>
 
 #include <SDL.h>
@@ -29,6 +30,19 @@
 	SDL_Delay(ms);
 }
 
+const char *
+pprintf(const char *fmt, ...)
+{
+	static char path[PATH_MAX];
+	va_list ap;
+
+	va_start(ap, fmt);
+	vsnprintf(path, sizeof (path), fmt, ap);
+	va_end(ap);
+
+	return path;
+}
+
 unsigned int
 nrand(unsigned int lower, unsigned int upper)
 {
--- a/libcore/core/util.h	Thu Nov 26 18:00:45 2020 +0100
+++ b/libcore/core/util.h	Fri Nov 27 13:31:16 2020 +0100
@@ -50,6 +50,21 @@
 delay(unsigned int ms);
 
 /**
+ * Construct a temporary path to a file that can fit in a PATH_MAX array.
+ *
+ * This function is useful when specifying paths into a function invocation such
+ * as `fopen(pprintf("%s.png", i), "r"))`.
+ *
+ * \pre fmt != NULL
+ * \param fmt the format string
+ * \warning This function is not reentrant, it returns a static storage path.
+ * \return A non null path to a file.
+ * \post Returned string is never NULL.
+ */
+const char *
+pprintf(const char *fmt, ...);
+
+/**
  * Generate a random number between lower and upper (included).
  *
  * \pre upper must be <= RAND_MAX