C: Add sdprintf

This commit is contained in:
Markus Koch 2020-05-03 20:10:05 +02:00
parent 4647847eb3
commit 25d2b25335
2 changed files with 25 additions and 2 deletions

View File

@ -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

23
c/sdprintf.c Normal file
View File

@ -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;
}