在我使用的程序中,我有一个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());
Run Code Online (Sandbox Code Playgroud)
这意味着我将我的cout重定向到一个文件.将cout返回标准输出的最简单方法是什么?
谢谢.
在改变streambuf之前保存旧cout
的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!
Run Code Online (Sandbox Code Playgroud)
你可以写一个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
}
};
Run Code Online (Sandbox Code Playgroud)
现在根据范围使用它:
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!
Run Code Online (Sandbox Code Playgroud)
最后一个cout
输出到stdout
即使condition
是true
和if
块执行.