How to print both to stdout and file in C

Fortunately, you don’t need to. You just want to use the v variants of printf and fprintf that take a va_list instead of your passing arguments 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);
}

Leave a Comment