c++stdoutfclosefreopen

Writing to both terminal and file 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).


Solution

  • 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.