[ACCEPTED]-How to print both to stdout and file in C-file-io
Accepted answer
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);
}
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
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_list
s 2 and pass them both to vdupPrint
, which is a sub-optimal 1 solution but will work for C89 safely.)
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.