I am trying to use freopen() to print to a text file and the screen, but I am only achieving the printing to a file.
I was wondering if there was an easy to save the
The easy way in a UNIX-like environment is to use the shell command tee
:
$ my-program | tee output.txt
will copy stdout to the terminal, and also to the file output.txt
.
If you have to do it in code, you could use your own output stream instead of cout
, which forwards every operator<<
to two (or more) ostreams
. This feels nicer (to me) than mucking around with the C output file underlying the C++ ostream cout
.
#include
class Tee {
std::ostream &first, &second;
template friend Tee& operator<< (Tee&, T);
public:
Tee(std::ostream &f, std::ostream &s) : first(f), second(s) {}
};
template
Tee& operator<< (Tee &t, T val)
{
t.first << val;
t.second << val;
return t;
}
Then, if you replace your freopen line with:
std::ofstream outfile("file.txt");
Tee tee(std::cout, outfile);
you can just use tee <<
instead of cout <<
.
Note that you'll either need to pass tee
into your functions, or make it a global for that to work.