Reputation: 23501
I'm trying to create a printf function that print like this
[INFO] whatever 123
va_args works but I don't know how to add a prefix. At least the following code won't do
#include <stdio.h>
#include <stdarg.h>
void myprintf (char *fmt, ...)
{
va_list argp;
va_start (argp, fmt);
vfprintf (stdout, "[INFO] " fmt, argp);
va_end (argp);
}
int main (int argc , char **argv)
{
myprintf ("arg count is %d\n", argc);
return 0;
}
Any ideas?
Upvotes: 0
Views: 1531
Reputation:
"[INFO] " fmt
This code won't work. The "string pasting" behavior you're trying to use here is a preprocessor behavior, not a C operator. It can only be used on string constants -- not variables.
The easiest way of getting the behavior you want here will be to simply call printf
twice:
printf("[INFO] ");
va_start(argp, fmt);
vfprintf(stdout, fmt, argp);
va_end(argp);
More difficult approaches which you may want to consider include:
Define myprintf()
as a macro instead of a function so that it can use string pasting on the format argument.
Copy "[INFO] "
and fmt
into a temporary buffer and use that as a formatting string.
Copy "[INFO] "
into a temporary buffer, use vsnprintf()
to append the output to the buffer, then output that.
Upvotes: 3