C/C++ 標准輸入輸出重定向


轉載自:http://www.cnblogs.com/hjslovewcl/archive/2011/01/10/2314356.html

這個對經常在OJ上做題的童鞋們很有用。OJ基本都是用標准輸入輸出(USACO除外)。但如果你在調試的時候也都是從控制台輸入,那就太浪費寶貴的時間了。我們可以重定向標准輸入,調試的時候從文件讀,提交時從標准輸入讀。

在C語言中,方法比較簡單。使用函數freopen(): 

freopen("data.in","r",stdin);  
freopen("data.out","w",stdout);  

  

這樣就把標准輸入重定向到了data.in文件,標准輸出重定向到了data.out文件。

這兩句代碼之后,scanf函數就會從data.in文件里讀,而printf函數就會輸出到data.out文件里了。

C++中,對流重定向有兩個重載函數:

streambuf* rdbuf () const;  
streambuf* rdbuf (streambuf *)   

 就相當於get/set方法。

 

代碼示例:

 1 #include <iostream>
 2 #include <string>
 3 #include <fstream>
 4 
 5 using namespace std;
 6 
 7 int main(){
 8     string str;
 9     /*不同的string頭文件不一定都支持getline(cin,string);
10     char a[100];
11     cin>>a;
12     cout<<a<<endl;*/
13     streambuf * backup;
14     ifstream fin;
15     ofstream fout;
16     fout.open("data.txt");
17     backup = cout.rdbuf();
18     cout.rdbuf(fout.rdbuf());
19     //cin>>str;    /*有空格就會停止*/
20     getline(cin, str);    /*直到換行符處才停止*/
21     cout<<str<<endl;
22     cout.rdbuf(backup);
23     fout.close();
24     
25     str.clear();
26     fin.open("data.txt");
27     backup = cin.rdbuf();
28     cin.rdbuf(fin.rdbuf());
29 
30     cin>>str;
31     cout<<str<<'!'<<endl;
32     cin.rdbuf(backup);
33     
34     fin.close();
35     return 0;
36 }

 

注意最后我們使用了cin.rdbuf(backup)把cin又重定向回了控制台

然而,如果用C語言實現同樣的功能就不那么優雅了。

因為標准控制台設備文件的名字是與操作系統相關的。

在Dos/Windows中,名字是con

  freopen("con", "r", stdin);

在Linux中,控制台設備是/dev/console

  freopen("/dev/console", "r", stdin);

另外,在類unix系統中,也可以使用dup系統調用來預先復制一份原始的stdin句柄。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM