When looking for how to wrap a function with variadic length argument, what I often see as an answer is not a solution but a workaround. Let's change the example from printf
to a function printfln
written in a library and I have no control over the library and I cannot add anything there. Now, I have another function double_printfln
that should call printfln
two times. This time we cannot use vprintf
workaround.
How to do this?
https://wandbox.org/permlink/q8wF51qLu8JdYv0o
#include <stdio.h>
#include <stdarg.h>
int printfln(const char *format, ...)
{
int result;
va_list args;
va_start(args, format);
result = vprintf(format, args);
printf("\n");
va_end(args);
return result;
}
int double_printfln(const char *format, ...)
{
int result;
va_list args;
va_start(args, format);
result = printfln(format, args);
result += printfln(format, args);
va_end(args);
return result;
}
int main()
{
int x=7;
char text[20] = "Hello";
double_printfln("%s, %d", text, x);
return 0;
}
Solution
For those who face with a similar problem, this is how I fixed it. This is actually another workaround but in a better way:
int double_printfln(const char *format, ...)
{
char line[512];
int result;
va_list args;
va_start(args, format);
memset(line, 0x00, sizeof line);
vsprintf(line, format, args);
va_end(args);
result = printfln(line);
result += printfln(line);
return result;
}