From 25d2b25335bd9ba95631d901c55464d5f957f587 Mon Sep 17 00:00:00 2001 From: Markus Koch Date: Sun, 3 May 2020 20:10:05 +0200 Subject: [PATCH] C: Add sdprintf --- README.MD | 4 ++-- c/sdprintf.c | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 c/sdprintf.c diff --git a/README.MD b/README.MD index 8d61aae..5ec5a22 100644 --- a/README.MD +++ b/README.MD @@ -2,5 +2,5 @@ Small code snippets that might prove useful again in the future. ## C -* report: Easy to use report statement with log levels - +* report/: Easy to use report statement with log levels +* sdprintf.c: sprintf to a dynamic buffer diff --git a/c/sdprintf.c b/c/sdprintf.c new file mode 100644 index 0000000..26b7bdd --- /dev/null +++ b/c/sdprintf.c @@ -0,0 +1,23 @@ +/*! + * \brief sdprintf printf to a dynamic buffer + * \param buf The character buffer. Will append if not NULL; + * \param offset Should be set to strlen when continuing a string. Will be incremented automatically. + * \param __format printf format string + * \return the number of bytes written + */ +int sdprintf(char **buf, int *offset, const char *__restrict __format, ...) +{ + va_list vargs; + int len; + + va_start(vargs, __format); + len = vsnprintf(NULL, 0, __format, vargs); + va_end(vargs); + *buf = realloc(*buf, *offset + len + 1); + va_start(vargs, __format); + len = vsprintf(*buf + *offset, __format, vargs); + va_end(vargs); + + *offset += len; + return len; +}