简体   繁体   English

在 std::ofstream (c++) 中复制 std::cout

[英]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 内容复制到 std::ofstream 中以制作“日志”文件以打印我发送到 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.txt 有:

[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).每个 stream object 只能绑定到单个缓冲区,并且std::cout不 go 向后(可以写入,但不能读取)。

Because of that, while you can redirect cout to go to any other stream, this will only be effective for output happened after redirection.因此,虽然您可以将cout重定向到 go 到任何其他 stream,但这仅对重定向发生的 output 有效。 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).您绝对没有办法强制之前打印到cout的数据现在出现在任何其他 stream 中,除非您有办法重新创建数据或从其他存储(不是 cout)中提取数据。

You can simply create your own T (Tee) stream, by deriving your own class from a std::ostream .您可以通过从std::ostream派生您自己的 class 来简单地创建您自己的 T (Tee) stream。

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.这相当简单,基本上你只需要覆盖流syncoverflow function,并将数据发送到两个所需的输出。

You can find a complete example of a Tee stream here and here .您可以在此处此处找到 Tee stream 的完整示例。

In this example code, I select where the output goes to with command line options.在此示例代码中,我 select output 与命令行选项一起使用。 And, the beauty of it, you can use all existing IO-stream facilities.而且,它的美妙之处在于,您可以使用所有现有的 IO-stream 设施。 And, it is fully transparent.而且,它是完全透明的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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