3

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

谢谢。

4

1 回答 1

9

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

最后一个cout将输出到stdout即使conditiontrue并且if块被执行。

于 2012-08-29T18:30:14.140 回答