首页 > 编程语言 > 详细

C/C++-标准输入/输出重定向为文件输入/输出

时间:2017-02-22 12:49:37      阅读:350      评论:0      收藏:0      [点我收藏+]
/*
    Time: 2017-02-22 11:11:15
    Describe: C++程序将标准输入/输出重定向为文件输入/输出。
*/

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
 
void f()
{
    string line;
    while(getline(cin, line))  //input from the file in.txt
    {
        cout << line <<endl;   //output to the file out.txt
    }
}

// TEST ONE.
int main()
{
    ifstream in("in.txt");
    streambuf *backinbuf = cin.rdbuf(); //save old buf
    cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
 
    ofstream out("out.txt");
    streambuf *backoutbuf = cout.rdbuf(); //save old buf
    cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
 
    // ONE.
    f(); //call function
}

// TEST TWO.
/*
int main()
{
    ifstream in("in.txt");
    streambuf *backinbuf = cin.rdbuf(); //save old buf
    cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
 
    ofstream out("out.txt");
    streambuf *backoutbuf = cout.rdbuf(); //save old buf
    cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    // TWO.
    string word;
    cin >> word;           //input from the file in.txt
    cout << word << "--";  //output to the file out.txt
}
*/

// TEST THREE.
/*
int main()
{
    ifstream in("in.txt");
    streambuf * backinbuf = cin.rdbuf(); //save old buf
    cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!
 
    ofstream out("out.txt");
    streambuf * backoutbuf = cout.rdbuf(); //save old buf
    cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    // DO SOMETHING...... (redirect.)

    // RESET.
    cin.rdbuf(backinbuf);   //reset to standard input again
    cout.rdbuf(backoutbuf); //reset to standard output again
 
    // THREE.
    cin >> word;   //input from the standard input
    cout << word;  //output to the standard input
}
*/

  

C/C++-标准输入/输出重定向为文件输入/输出

原文:http://www.cnblogs.com/hfultrastrong/p/6427975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!