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

のstreambuf を変更する前に、古い streambuf を保存しますcout

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これを自動的に行う to を次のように記述できます。

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に出力されます。stdoutconditiontrueif

于 2012-08-29T18:30:14.140 に答える