2012-08-29 84 views
3

後COUT我在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返回到標準輸出的最簡單方法是什麼?

謝謝。

回答

8

保存舊的流緩衝您更改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自動做,因爲:

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塊。