Redirect printf to TWO streams

I am extending an existing C project that prints all the information up to stdout

with printf

. I would like this information to be printed for both stdout AND and log file.

If I was the author of the original project, I would simply replace all calls with printf

my custom log function. Alas I am not, so here is my question:

Is it possible to redirect printf

to have one call print both values ​​to stdout

and to a file?

I know this is a long shot, but if it were possible, I could get what I want without changing the source code.

EDIT: Thank you for your response and team comments tee

. However, I'm looking for a way to do it right in C code, in an automated way, so users don't have to worry about using tee.

Thanks for your attention!

+3


source to share


3 answers


Not sure if this will help, but a similar question appears frequently in the comp.lang.c listing:

http://c-faq.com/stdio/multiway.html



Bottom line: you can write your own "twowayprintf" function and then call it, but there is no way from within the program to arrange regular printf calls in two places. If you want to keep the existing printf calls, you will have to work outside of the program (with shell scripts and / or the tee command) as described by others.

+2


source


You are looking for the tee command :

./prog | tee file

      

This will show the output ./prog

in stdout

, and it will also save it to file

. Think about tee

as a tee in plumbing :)



UPDATE

If you don't want to force users to think about using tee

, I would just make a shell script that does exactly what I showed above - call the program with tee

- and ask users to interact with just the script.

If this doesn't work for you and you really want to change the source, I don't see an immediate easy solution. You can write a wrapper printf()

that writes to two threads, but then you have to go ahead and replace each call printf()

with your wrapper.

+7


source


You can write a simple wrapper program that:

  • Creates a channel and forks:
    • in the child process closes the output side of the pipe, reopens stdin

      as the input side of the pipe and exec()

      tee

      , giving it the corresponding argv vector (logfile name)
    • in the parent process, closes the input side of the channel, reopens the original executable stdout

      as the output side of the channel exec()

      .
+1


source







All Articles