【问题标题】:Switching cout back to writing to the screen将 cout 切换回写入屏幕
【发布时间】:2021-04-05 23:06:58
【问题描述】:

在我的程序中,我将 cout 切换为使用以下命令写入文件:

int newstdout = open("myFile.txt",O_WRONLY|O_CREAT,S_IRWXU|S_IRWXG|S_IRWXO);    
close(1);    
dup(newstdout);    
close(newstdout);

稍后我将如何在程序中切换回我的 cout 打印到屏幕(终端)?

【问题讨论】:

标签: c++ cout


【解决方案1】:

cout(或任何其他流)输出到不同目标的正确方法是调用其rdbuf() 方法来交换不同的流缓冲区。如果需要,您可以稍后换回旧缓冲区。例如:

#include <iostream>
#include <fstream>

std::ofstream outfile("myFile.txt");
auto cout_buff = std::cout.rdbuf();

std::cout.rdbuf(outfile.rdbuf());
// anything written to std::cout will now go to myFile.txt instead...

std::cout.rdbuf(cout_buff);
// anything written to std::cout will now go to STDOUT again...

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    相关资源
    最近更新 更多