简体   繁体   中英

Copy std::cout inside a std::ofstream (c++)

i am currently trying to make a very basic "logging system" and I would like to copy std::cout contents inside a std::ofstream to make a "log" file to print what i sent to the cout.

std::cout << "[LOG] My log message\n";
std::cout << "[LOG] My log message2\n";
std::ofstream s("Log.txt");
//std::cout >> s; ????????????

This is how i tried to do it but without success. I expect Log.txt to have:

[LOG] My log message
[LOG] My log message2

You can't have a cake and eat it in the same time. Each stream object can only be tied to a single buffer, and std::cout does not go backwards (you can write to it, but you can't read from it).

Because of that, while you can redirect cout to go to any other stream, this will only be effective for output happened after redirection. There is absolutely no way for you to force the data which was printed to cout before to appear in any other stream now , unless you have a way to recreate the data or extract it from some other storage (not cout).

You can simply create your own T (Tee) stream, by deriving your own class from a std::ostream .

That is rather simple and basically you just need to override the streams sync and overflow function, and send the data to both desired outputs.

You can find a complete example of a Tee stream here and here .

In this example code, I select where the output goes to with command line options. And, the beauty of it, you can use all existing IO-stream facilities. And, it is fully transparent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM