2

Recently I wanted to implement a printf wrapper. After some search I found the vprintf is good for this need:

void my_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

But is it possible to implement such a wrapper for printf or any other similar functions with variable arguments instead of va_list?

(I mean, what if they don't provide a v version?)


Since some commenter didn't fully capture my idea, I'd better elaborate it.

Suppose you have a plain printf function as in the C library.

Some one gives you a fmt string "%d %u %f", and corresponding inputs.

Now you want to write a function similar to printf, but with all %f replaced by %.2f.

Of course you can use two statements to finish the task:

replace(fmt, "%f", "%.2f");
printf(fmt, inputs);

But if you use this function many times, probably you want to have a wrapper to save some time.

A macro can finish this task, of course. But is it possible without a macro, like:

void myprintf(fmt, ...)
{
    replace(fmt, "%f", "%.2f");
    printf(fmt, inputs);
}

The problem here is that you don't know how to feed the inner printf with the arguments ... of myprintf.

Hope this clarifies.

Cyker
  • 9,946
  • 8
  • 65
  • 93
  • I cannot understand what you really want. Do you want to have variables arguments without having to use `va_list`? – Pablo Oct 18 '12 at 12:44

2 Answers2

3

If you just want to use this to prepend an string to the output or so, you could use a variadic macro.

#define MYPRINT(...) printf("toto has: " __VA_ARGS__)

in that simple example this suppposes that format that you pass in is a string literal, so this is a bit restricted. But I hope you see the pattern how to use such simple macro wrappers.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
2

There is no portable way to construct a call to a variadic function when the API don't offer you functions with va_list parameter.

However, you could [ab]use the libffi for that purpose, by constructing the variadic call and doing it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547