将cout切换回在屏幕上书写

Switching cout back to writing to the screen

本文关键字:屏幕 书写 cout      更新时间:2024-05-23

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

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

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

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