Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect printf to TWO streams

Tags:

c

I am extending an existing C project that prints all information to stdout with printf. I would like to have this information printed both to stdout AND to a log file.

If I were a contributor to the original project, I would just substitute all printf calls with my custom log function. Alas, I am not, so here's my question:

Is it possible to redirect printf so that a single call prints both to stdout and to file?

I know this is a long shot but, if it were possible, I could obtain what I want without having to modify the original code.

EDIT: Thank you for the answer and comments about the tee command. However, I am looking for a way to do it directly in the C code, in an automated fashion, so that users won't have to bother using tee.

Thank you for your attention!

like image 735
Guido Walter Pettinari Avatar asked Sep 02 '25 15:09

Guido Walter Pettinari


1 Answers

You're looking for the tee command:

./prog | tee file

This will show the output of ./prog in stdout and it will also store it in file. Think of tee as a tee fixture 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 precisely what I showed above - invoke the program with tee - and have users interact with the script only.

If that doesn't work for you, and you really want to change the source, I don't see any immediate easy solution. You could write a printf() wrapper that writes into the two streams, but then you'd have to go ahead and replace every call to printf() to your wrapper.

like image 101
Filipe Gonçalves Avatar answered Sep 05 '25 04:09

Filipe Gonçalves