C++ 中的 I/O 重定向
在 C 中,我們可以使用 freopen() 函式進行重定向。使用此函式,我們可以將現有 FILE 指標重定向到另一個流。freopen 的語法如下
FILE *freopen(const char* filename, const char* mode, FILE *stream)
同樣地,在 C++ 中,我們也可以進行重定向。在 C++ 中,使用流。這裡我們可以使用我們自己的流,也可以重定向系統流。在 C++ 中,有三種類型的流。
- istream:只能支援輸入的流
- ostream:只能支援輸出的流
- iostream:這些可以用於輸入和輸出。
這些類和檔案流類衍生自 ios 和 stream-buf 類。因此,檔案流和 IO 流物件的行為類似。C++ 允許將流緩衝區設定為任何流。因此,我們可以簡單地更改與流關聯的流緩衝區進行重定向。例如,如果有兩個流 A 和 B,並且我們要將流 A 重定向到流 B,我們需要按照以下步驟進行操作
- 獲取流緩衝區 A 並存儲
- 將流緩衝區 A 設定為另一個流緩衝區 B
- 將流緩衝區 A 重置為其先前位置(可選)
示例程式碼
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { fstream fs; fs.open("abcd.txt", ios::out); string lin; // Make a backup of stream buffer streambuf* sb_cout = cout.rdbuf(); streambuf* sb_cin = cin.rdbuf(); // Get the file stream buffer streambuf* sb_file = fs.rdbuf(); // Now cout will point to file cout.rdbuf(sb_file); cout << "This string will be stored into the File" << endl; //get the previous buffer from backup cout.rdbuf(sb_cout); cout << "Again in Cout buffer for console" << endl; fs.close(); }
輸出
Again in Cout buffer for console
abcd.txt
This string will be stored into the File
廣告