重定向,就是:
把 原来的 cin 从键盘输入 改为从文件输入。
把 原来的 cout 向屏幕输出 改为输出到文件。
例如: cin>>line; 原来要从键盘拍入。现在自动到某文件读取,语句还是 cin>>line; 不变。
cout << line << endl; 原来向屏幕输出,现在自动写到某文件里,语句还是cout << line << endl;不变
=======
C++ 实现方法:
#include <iostream> #include <ostream> #include <fstream> using namespace std; main() { ifstream fin("input.txt"); // 已有输入文件 ofstream fout("output.txt"); //输出文件 streambuf *cinbackup; streambuf *coutbackup; coutbackup= cout.rdbuf(fout.rdbuf()); //用 rdbuf() 重新定向 cinbackup= cin.rdbuf(fin.rdbuf()); //用 rdbuf() 重新定向 cout<<"Hello world"<<endl; //去文件也 char line[100]; cin>>line; //从input.txt文件读入 cout<<line<<endl; //写入 output.txt // restore standard streambuf cin.rdbuf(cinbackup); // 取消,恢复键盘输入 cout.rdbuf(coutbackup); //取消,恢复屏幕输出 return 0; }