重定向后重置cout

时间:2012-08-29 18:27:00

标签: c++ outputstream

在我使用的程序中,我有一个用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返回标准输出的最简单方法是什么?

感谢。

1 个答案:

答案 0 :(得分:8)

在更改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!

即使coutstdout并且condition块已执行,最后true也会输出到if