[ACCEPTED]-How to print both to stdout and file in C-file-io

Accepted answer
Score: 14

Fortunately, you don't need to. You just 3 want to use the v variants of printf and fprintf that 2 take a va_list instead of your passing arguments 1 directly:

void tee(FILE *f, char const *fmt, ...) { 
    va_list ap;
    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
    va_start(ap, fmt);
    vfprintf(f, fmt, ap);
    va_end(ap);
}
Score: 3

You can implement your dupPrint function using vfprintf and 1 va_list/ va_start / va_end.

Score: 3

in the mid-layer:

#define DUPPRINT(fp, fmt...) do {printf(fmt);fprintf(fp,fmt);} while(0)

in your app code:

...
DUPPRINT(fd, "%s:%d\n", val_name, val_v);
...

0

Score: 2

Use a variadic function and vprintf!

void dupPrint(FILE *fp,char *fmt,  ...)
{
    va_list ap;

    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);

    va_start(ap, fmt);
    vfprintf(fp, fmt, ap);
    va_end(ap);
}

Optionally, implement 6 vdupPrint, have dupPrint call vdupPrint, and use va_copy (if C99 is available) to 5 duplicate the va_list instead of the stop-and-restart 4 method I used. (If va_copy is not available to 3 you, you'll have to start two separate va_lists 2 and pass them both to vdupPrint, which is a sub-optimal 1 solution but will work for C89 safely.)

More Related questions