0

I have a program where I want to duplicate some of the output to stdout in a text file for caching. It looks something like this:

FILE* cache;
// Open file, check for errors, etc.
fprintf(stdout, "My data\n");
fprintf(cache, "My data\n");
for (int i = 0; i < 10; ++i)
{
    fprintf(stdtout, "%d ", i);
    fprintf(cache, "%d ", i);
}

Is there some way to get a FILE * where if I write to it, I get output in both stdout and my cache file?

(It doesn't work to just redirect it in the shell; the program needs to decide this, not the caller.)

1 Answers1

2

A FILE object is associated with one file only, so you can't write to one FILE and have it write to two physical files.

What you can do however is create a wrapper around fprintf that takes two FILE * and do the duplication there.

void dup_fprintf(FILE *f1, FILE *f2, const char *format, ...)
{
    va_list args1;
    va_start(args1, format);
    vfprintf(f1, format, args1);
    va_end(args1);

    va_list args2;
    va_start(args2, format);
    vfprintf(f2, format, args2);
    va_end(args2);
}

Then you can do this:

dup_fprintf(stdout, cache, "My data\n");
for (int i = 0; i < 10; ++i)
{
    dup_fprintf(stdtout, cache, "%d ", i);
}
dbush
  • 205,898
  • 23
  • 218
  • 273