重定向后重置cout

Resetting the cout after redirection

本文关键字:cout 重定向      更新时间:2023-10-16

我在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!

即使conditiontrue并且执行if块,最后的cout也将输出到stdout