IO 重定向

std::ios::rdbuf

streambuf* rdbuf() const;(1)
streambuf* rdbuf (streambuf* sb);(2)

形式(1)返回一个指向当前与流关联的流缓冲区对象的指针。
形式(2)将sb指向的对象设置为与流关联的流缓冲区,并清除错误状态标志。
一些派生流类(例如stringstream和fstream)维护它们自己的内部流缓冲区,它们在构建时与其相关联。调用此函数来更改关联的流缓冲区应该对该内部流缓冲区没有影响:该流将具有与其内部流缓冲区不同的关联流缓冲区(尽管流上的输入/输出操作始终使用关联的

一般有3种操作:

  1. 获取Stream A的流缓冲区并将其存储在某处
  2. 将A的流缓冲区设置为B的流缓冲区
  3. 将A的流缓冲区重置为原来的流缓冲区
#include 
#include 
#include 

using namespace std;

int main()
{
    ifstream infile("hello.in");
    streambuf *cinbuf = infile.rdbuf();//保存原来的buffer
    //auto cinbuf = cin.rdbuf(infile.rdbuf());同上 效果一样
    cin.rdbuf(infile.rdbuf());//将cin 重定向 到infile


    ofstream outfile("hello.out");
    streambuf *outbuf = outfile.rdbuf();
    cout.rdbuf(outfile.rdbuf());

    string line;
    while (std::getline(cin, line))  // 内容来自hello.in
    {
        cout << line << "\n";   //输出到hello.out
    }

    cin.rdbuf(cinbuf);
    cout.rdbuf(outbuf);

    system("pause");
    return 0;
}

参考:
cpp
geeksforgeeks
stackoverflow

你可能感兴趣的:(io,重定向)