Search code examples
clinuxstdoutio-redirectiontee

C redirect standard output to several places


It is rather easy to redirect output to another destination. I can easily achieve that with:

freopen ("/def/tty0", "w", stdout);
printf ("Redirected");
fclose (stdout);

But how could I redirect it to two or more files? I need functionality similar to this provided by "tee".

Is there any well known approach?


Solution

  • This is not possible to do directly: Each file descriptor is assigned to exactly one resource (typically a file). If you want a write to a FILE yield in writes to multiple files, you have to do some tricks. Here are some ideas:

    • Use the GNU-only function fopencookie(3) to make a FILE* that actually outputs to more than one file. See the manpage of fopencookie(3) for more details.
    • Make a pipe, then fork. The forked process reads from the pipe and writes what it reads into all the files you want. The original process writes to the pipe.
    • Invoke tee(1) with suitable arguments and write the data to the standard input of tee(1). Have a look at popen(3) for a useful function to do that.