Colin said:
I'm trying to write a function that is a wrapper for printf. It looks
something like:
myprintf(int myarg1, int myarg2, const char* fmt, ...)
{
/* Do something with myarg1, myarg2 *.
.
.
.
printf(fmt, ?)
}
I'm not sure how to pass the variable arguments on to printf. Any
help?
Thanks,
Colin
Hi,
I just learned this recently myself, you use vprintf, that's what
vprintf does. Instead of being prototyped with the ellipsis like
printf:
int printf(char* fmt, ...);
it's prototyped with a variables arguments or varargs list, va_list.
int vprintf(char* fmt, va_list ap);
So, ...:
#include <stdio.h>
#include <stdarg.h>
int myprintf(int x, int y, char* fmt, ...){
int retval=0;
va_list ap;
va_start(ap, fmt); /* Initialize the va_list */
x = y; /* Use the variables, (void)x;(void)y; */
retval = vprintf(fmt, ap); /* Call vprintf */
va_end(ap); /* Cleanup the va_list */
return retval;
}
You always have to call va_start and va_end on the argument list, the
va_list.
I think that's right, I could be wrong.
I think it's a good idea to avoid using the varargs facility, because
it leads to knowledge of how the compiler pushes function arguments
onto the stack, but if you're using the printf facility it's good for
that.
A great book for C is Harbison and Steele's "C: A Reference Manual",
it's not easy to find a clear description of the varargs facility, that
otherwise good text doesn't have one, but it's my favorite C book.
Warm regards,
Ross F.