-
Args after varargs
Hi all,
Have a lil problem here,
I have a function prototype that looks a little like this
log(char *app, char *msg, char *user, int flag)
I was then told to include var args for msg, so that people can log data with the olde %d, %s etc.
Now id i use var args, how do i ensure that the last 2 variables get passed?
I cannot change the ordering as a lot of programs depend on it
Advise,
Arun
-
Well you could still use varargs, except that perhaps the interface would be a little less intuitive since the arguments would be appended with two arguments in between them and the format string.
-
varargs doesn't depend on the format string being the last parameter.
Code:
#include <stdio.h>
#include <stdarg.h>
void __attribute__ ((format (printf, 2, 5)))
log(char *app, char *msg, char *user, int flag, ... )
{
va_list ap;
va_start(ap,flag);
printf("App=%s, user=%s, flag=%d\n",app,user,flag);
vprintf(msg,ap);
printf("\n");
va_end(ap);
}
int main()
{
log("main", "Hey %s %d", "me", 42, "A message", 1234 );
return 0;
}
If you're using gcc, then you'll want to keep the __attribute__ thing so that you get free checking of the variable parameters (just like if you were using regular printf).
-
Hi,
Thanks for the replies. But the problem now is that my logging apparatus becomes very non intuitve to use, as the formatting parameters are at the very end.
Output for your code snippet:
App=main, user=me, flag=42
Hey A message 1234
Rather, is there a way to find out the number of arguments that have been passed to a function, so I may capture the last 2 and proceed to process the rest?
Arun
-
So use vsnprintf() to format msg and the variable arguments into a buffer, then use that buffer along with the rest of the parameters in the way you're doing it at the moment.
-
Hey, do we get a mention in your commercial product?