Reputation: 3413
I have a debug function that takes a format and variable number of additional arguments (just like printf()
), converts them to a formatted string stored in a buffer buf
, and sends that buffer to a secondary function that actually prints it:
#include <stdio.h>
#include <stdarg.h>
void debug_printf(const char *fmt, ...)
{
char buf[100];
va_list va;
va_start(va, fmt);
/* Format the string and store it in buf */
vsnprintf(buf, sizeof(buf), fmt, va);
/* Actually print the buf. */
actual_print(buf);
va_end(va);
}
How can I modify this function to prepend a string to the resulting output? For example, a header like DBG:
so that if I called debug_printf("test1")
the result would print DBG: test1
.
Alternatively, how can I modify this function take a variable integer (the return value of a function) and somehow prepend that as a string to the resulting output? For example, if I had a function rng()
that returned a random integer, I might call debug_printf("test2")
and the result would print something like 3572 test2
, assuming rng()
returned integer value 3572
.
For both cases, ideally the solution will modify the body of debug_printf()
rather than wrap it in another function and/or a preprocessor macro.
EDIT: It appears I forgot an important point. For performance reasons, I would greatly prefer to only call actual_printf()
once within debug_printf()
. Otherwise yes, it would be a fairly easy solution to call it twice: Once with the header and again with the actual formatted string. Sorry about that!
Upvotes: 1
Views: 515
Reputation: 6079
Print into buf whatever you want to prepend and that's it.
#include <stdio.h>
#include <stdarg.h>
void debug_printf(const char *fmt, ...)
{
char buf[100];
va_list va;
va_start(va, fmt);
int n = snprintf(buf, sizeof(buf), "DBG: ");
/* Format the string and store it in buf */
vsnprintf(buf + n, sizeof(buf) - n, fmt, va);
/* Actually print the buf. */
actual_print(buf);
va_end(va);
}
There's no need to use a fixed size. The manpage has an example to calculate the right size for the buffer to allocate with malloc():
http://man7.org/linux/man-pages/man3/printf.3.html
Upvotes: 2
Reputation: 6405
Instead of finding a complicated way to insert another parameter in the variadic list, you can just add a simple printf in the beginning of your code:
printf("%d ",rng());
Upvotes: 0