views:

130

answers:

1

I'm looking to write a function to replace fprintf

int fprintf ( FILE * stream, const char * format, ... );

I'm not sure how to define a function such as this, because, after the format parameter, this function takes a variable number of parameters. Specifically, it takes at least as many additional arguments as were specified in the format.

UPDATE I found a resource on the subject (http://publications.gbdirect.co.uk/c%5Fbook/chapter9/stdarg.html), but the example doesn't seem to compile under Linux, the OS that I'm using.

An example of a replacement for fprintf which just calls fprintf would be helpful.

This isn't homework. I'm just a beginner who is trying to learn how to program in his free time. Thanks!

+9  A: 

Instead of calling fprintf directly, you will need to call vfprintf instead. For example:

#include <stdarg.h>
int myfprintf(FILE *stream, const char *format, ...) {
    va_list args;
    va_start(args, format);
    int r = vfprintf(stream, format, args);
    va_end(args);
    return r;
}

In the standard library, every function that takes varargs (...) also has a v version of the same function that takes a va_list parameter. Since you can't construct arguments to pass to ... dynamically, you need to use the v variant to pass on the varargs.

Greg Hewgill