How can I arrange to have output go two places at once, e.g. to the screen and to a file?

Q

How can I arrange to have output go two places at once, e.g. to the screen and to a file?

✍: Guest

A

You can't do this directly, but you could write your own printf variant which printed everything twice. Here is a sample logprintf function which prints to both stdout and a preopened log file:
#include <stdio.h>
#include <stdarg.h>

extern FILE *logfp;
void logprintf(char *fmt, ...)
{
va_list argp; va_start(argp, fmt);
vfprintf(stdout, fmt, argp);
va_end(argp);
va_start(argp, fmt);
vfprintf(logfp, fmt, argp)
; va_end(argp);
}

Now, whenever you call logprintf (which you can call with format strings just like printf), it prints both to stdout and to logfp, which you have presumably opened to your desired log file. Another way to arrange this would be

void f2printf(FILE *fp1, FILE *fp2, char *fmt, ...)
{
va_list argp;
va_start(argp, fmt); vfprintf(fp1, fmt, argp); va_end(argp);
va_start(argp, fmt); vfprintf(fp2, fmt, argp); va_end(argp);
}
where f2printf is just like fprintf except that you give it two file pointers (e.g. stdout and logfp) and it prints to both of them.
Both of these techniques obviously require you to use explicit calls to logprintf or f2printf. There is no known way in Standard C to arrange implicitly (i.e. via some call analogous to freopen) that one stream, which you print to once with a normal call like fprintf, print to two places at once.

2015-09-29, 801👍, 0💬