重定向后重置cout
Resetting the cout after redirection
我在c++中有一个程序,在我使用的程序中:
static ofstream s_outF(file.c_str());
if (!s_outF)
{
cerr << "ERROR : could not open file " << file << endl;
exit(EXIT_FAILURE);
}
cout.rdbuf(s_outF.rdbuf());
这意味着我将我的cout重定向到一个文件。将cout返回到标准输出的最简单方法是什么?
谢谢。
在更改cout
的streambuf:之前保存旧的streambuf
auto oldbuf = cout.rdbuf(); //save old streambuf
cout.rdbuf(s_outF.rdbuf()); //modify streambuf
cout << "Hello File"; //goes to the file!
cout.rdbuf(oldbuf); //restore old streambuf
cout << "Hello Stdout"; //goes to the stdout!
您可以编写一个restorer
来自动执行此操作,如下所示:
class restorer
{
std::ostream & dst;
std::ostream & src;
std::streambuf * oldbuf;
//disable copy
restorer(restorer const&);
restorer& operator=(restorer const&);
public:
restorer(std::ostream &dst,std::ostream &src): dst(dst),src(src)
{
oldbuf = dst.rdbuf(); //save
dst.rdbuf(src.rdbuf()); //modify
}
~restorer()
{
dst.rdbuf(oldbuf); //restore
}
};
现在根据范围使用它作为:
cout << "Hello Stdout"; //goes to the stdout!
if ( condition )
{
restorer modify(cout, s_out);
cout << "Hello File"; //goes to the file!
}
cout << "Hello Stdout"; //goes to the stdout!
即使condition
是true
并且执行if
块,最后的cout
也将输出到stdout
。
相关文章:
- 重定向到文件的C ++ COUT比使用Ofstream慢
- 为什么这个 RAII cout 重定向器不起作用:
- 将 std::cout 从单独线程中的 DLL 重定向到 QTextEdit
- C 忽略某些输出的COUT重定向
- std :: cout的重定向范围
- 将COUT从C 中的各种来源重定向到同一文件
- 重定向std:cout到std::ofstream,得到一个错误
- 当程序作为服务运行时重定向 std::cout
- 如何在窗口中重定向 std::cout 和 printf
- o是否可以将"cout"重定向到文件中?
- 重定向后重置cout
- C++通过重定向 cout 将标准输出复制到文件
- 重定向和时间戳标准::cout
- 将 printf 和 cout 重定向到套接字
- 重定向 std::cout 到 QTextEdit
- 使用std::ofstream写入文件的速度比使用std::cout慢,然后将输出重定向到日志文件
- Qt重定向输出从cout到qDebug
- 如何在c++中检查std::cout是否被重定向到文件
- 将std::cin直接重定向到std::cout
- 将C++生成的cerr和cout重定向到Ubuntu中的同一文件