《C++標准程序庫》 13.10.3 將標准 Streams 重新定向(Redirecting)
通過“設置 stream 緩沖區”來重定向某個 sream。“設置 stream 緩沖區”意味 I/O stream 的重定向可由程控,不必借助操作系統。
1 #include <iostream> 2 #include <fstream> 3 4 using namespace std; 5 6 void Redirect(ostream &); 7 8 int main() 9 { 10 cout << "the first row" << endl; 11 12 Redirect(cout); 13 14 cout << "the last row" << endl; 15 16 return 0; 17 } 18 19 void Redirect(ostream &strm) 20 { 21 ofstream file("redirect.txt"); 22 23 // save output buffer of the stream 24 streambuf *strm_buffer = strm.rdbuf(); 25 26 // redirect output into the file 27 strm.rdbuf(file.rdbuf()); 28 29 file << "one row for the file" << endl; 30 strm << "one row for the stream" << endl; 31 32 // restore old output buffer 33 strm.rdbuf(strm_buffer); 34 } // closes file AND its buffer automatically
程序輸出:
the first row
the last row
文件內容:
1 one row for the file 2 one row for the stream
值得注意的是,在 void Redirect(ostream &) 中的 file 是局部對象,在函數結束時被銷毀,相應的 stream 緩沖區也一並被銷毀。這和標准的 streams 不同,因為通常 file streams 在構造過程分配 stream 緩沖區,並於析構時銷毀它們。所以以上例子中的 cout 不能在被用於寫入。事實上它甚至無法在程序結束時被安全銷毀。因此我們應該保留舊緩沖區並於事后恢復。
——EOF——