Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

I/O Redirection ใน C++

ใน C ใช้ freopen() สำหรับ redirection เปลี่ยน FILE pointer ไปยัง stream อื่น ไวยากรณ์:

FILE *freopen(const char* filename, const char* mode, FILE *stream)

ใน C++ ใช้ streams มี 3 ประเภท:

  • istream: รองรับ input เท่านั้น
  • ostream: รองรับ output เท่านั้น
  • iostream: ใช้ input และ output ได้

คลาสเหล่านี้และ file stream classes มาจาก ios และ streambuf ดังนั้น filestream และ IO stream objects พฤติกรรมคล้ายกัน C++ อนุญาตให้ตั้งค่า stream buffer ให้ stream ใดก็ได้ จึงเปลี่ยน stream buffer เพื่อ redirect ได้

ตัวอย่าง: มี stream A และ B ต้องการ redirect A ไป B:

  • เก็บ stream buffer ของ A ไว้
  • ตั้งค่า stream buffer ของ A เป็นของ B
  • คืนค่า stream buffer ของ A กลับไป (ถ้าต้องการ)

ตัวอย่างโค้ด

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() {
    fstream fs;
    fs.open("abcd.txt", ios::out);
    string lin;
    // สำรอง stream buffer
    streambuf* sb_cout = cout.rdbuf();
    streambuf* sb_cin = cin.rdbuf();
    // ดึง file stream buffer
    streambuf* sb_file = fs.rdbuf();
    // ตอนนี้ cout ชี้ไปไฟล์
    cout.rdbuf(sb_file);
    cout << "This string will be stored into the File" << endl;
    // คืน buffer เดิม
    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