IO Redirection in C++ (redirect cin/cout to file stream, and restore)

来源:互联网 发布:gabrielle名字 知乎 编辑:程序博客网 时间:2024/06/06 00:29
Author: YuMaNzI  2014/01/19
#include <iostream>#include <fstream>#include <string>void f(){    std::string line;    while(std::getline(std::cin, line))  //input from the file in.txt    {        std::cout << line << "\n";   //output to the file out.txt    }}int main(){    std::ifstream in("in.txt");    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!    std::ofstream out("out.txt");    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!    std::string word;    std::cin >> word;           //input from the file in.txt    std::cout << word << "  ";  //output to the file out.txt    f(); //call function    std::cin.rdbuf(cinbuf);   //reset to standard input again    std::cout.rdbuf(coutbuf); //reset to standard output again    std::cin >> word;   //input from the standard input    std::cout << word;  //output to the standard input}
0 0
原创粉丝点击