1. 程式人生 > >標準輸入輸出重定向

標準輸入輸出重定向

函式名:freopen 
宣告:FILE *freopen( const char *path, const char *mode, FILE *stream ); 
所在檔案: stdio.h 
引數說明: 
path: 檔名,用於儲存輸入輸出的自定義檔名。 
mode: 檔案開啟的模式。
DESCRIPTION
       The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.
       The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):
       r      Open text file for reading.  The stream is positioned at the beginning of the file.
       r+     Open for reading and writing.  The stream is positioned at the beginning of the file.
       w      Truncate file to zero length or create text file for writing.  The stream is positioned at the beginning of the file.
       w+     Open for reading and writing.  The file is created if it does not exist, otherwise it is truncated.  The stream is positioned at the beginning of the file.
       a      Open for appending (writing at end of file).  The file is created if it does not exist.  The stream is positioned at the end of the file.
       a+     Open for reading and appending (writing at end of file).  The file is created if it does not exist.  The initial file position for reading is at the beginning
              of the file, but output is always appended to the end of the file.
stream: 一個檔案,通常使用標準流檔案,stdin, stdout, stderr。 
返回值:成功,則返回一個path所指定檔案的指標;失敗,返回NULL。(一般可以不使用它的返回值) 
功能:實現重定向,把預定義的標準流檔案定向到由path指定的檔案中。
標準流檔案具體是指stdin、stdout和stderr。其中stdin是標準輸入流,預設為鍵盤;stdout是標準輸出流,預設為螢幕;stderr是標準錯誤流,一般把螢幕設為預設。
例項:
#include <stdio.h> 
int main() { 
    int a,b; 
    freopen("debug\\in.txt","r",stdin); //輸入重定向,輸入資料將從in.txt檔案中讀取 
    freopen("debug\\out.txt","w",stdout); //輸出重定向,輸出資料將儲存在out.txt檔案中 
    while(scanf("%d %d",&a,&b)!=EOF) 
        printf("%d\n",a+b); 
    fclose(stdin);//關閉檔案
    fclose(stdout);//關閉檔案
    freopen("dev/console", "w", stdout);  //重新開啟輸出到螢幕,linux平臺
    freopen("dev/console", "r", stdin);   //重新定位到標準輸入,linux平臺
    return 0; 
}
python: 對print的輸出重定向:
import sys  
temp = sys.stdout  
file = open('f.txt','w')  
sys.stdout = file  
print (1,2,3)  
sys.stdout.close()  
sys.stdout = temp  
print (1,2,3)