Writing to both terminal and file c++

Aly picture Aly · Jan 20, 2014 · Viewed 9.2k times · Source

I found this question answered for Python, Java, Linux script, but not C++:

I'd like to write all outputs of my C++ program to both the terminal and an output file. Using something like this:

int main ()
{
freopen ("myfile.txt","w",stdout);
cout<< "Let's try this"; 
fclose (stdout);
return 0;
}

outputs it to only the output file named "myfile.txt", and prevents it from showing on the terminal. How can I make it output to both simultaneously? I use visual studio 2010 express (if that would make any difference).

Thanks in advance!

Answer

Vittorio Romeo picture Vittorio Romeo · Jan 20, 2014

Possible solution: use a static stream cout-like object to write both to cout and a file.

Rough example:

struct LogStream 
{
    template<typename T> LogStream& operator<<(const T& mValue)
    {
        std::cout << mValue;
        someLogStream << mValue;
    }
};

inline LogStream& lo() { static LogStream l; return l; }

int main()
{
    lo() << "hello!";
    return 0;
}

You will probably need to explicitly handle stream manipulators, though.

Here is my library implementation.