2011-07-24 172 views
6

我試圖在C中使用重定向將輸入重定向到一個文件,然後將標準輸出設置回打印到屏幕。有人能告訴我這段代碼有什麼問題嗎?你必須在c中重定向標準輸出,然後重置標準輸出

#include <stdio.h> 
#include <fcntl.h> 
#include <unistd.h> 

int main(int argc, char** argv) { 
    //create file "test" if it doesn't exist and open for writing setting permissions to 777 
    int file = open("test", O_CREAT | O_WRONLY, 0777); 
    //create another file handle for output 
    int current_out = dup(1); 

    printf("this will be printed to the screen\n"); 

    if(dup2(file, 1) < 0) { 
     fprintf(stderr, "couldn't redirect output\n"); 
     return 1; 
    } 

    printf("this will be printed to the file\n"); 

    if(dup2(current_out, file) < 0) { 
     fprintf(stderr, "couldn't reset output\n"); 
     return 1; 
    } 

    printf("and this will be printed to the screen again\n"); 

    return 0; 
} 
+1

有一個完全不同的方法來解決這個相同的問題在這裏:http://stackoverflow.com/questions/584868/rerouting-stdin-and-stdout-from-c。 – Sam

回答

3

你的第二個電話dup2是錯誤的,它改爲:

if (dup2(current_out, 1) < 0) { 
4

有一兩件事要確保做之前,將在所有的工作,是從下它切換stdout文件描述符之前調用fflush(stdout);。可能發生的情況是C標準庫正在緩衝你的輸出,而不知道你正在轉移它下面的文件描述符。您使用printf()編寫的數據不是實際上是發送到底層文件描述符,直到其緩衝區變滿(或您的程序從main返回)。

插入這樣的電話:

fflush(stdout); 
    if(dup2(file, 1) < 0) { 

兩個呼叫dup2()之前。

+0

我不認爲這是OP的問題,但它是非常好的建議,每當將stdio與文件描述符io混合時,幾乎總是應該遵循。 –

+1

的確如此,實際上我沒有注意到不正確的文件描述符,直到有人提到它。在寫入終端時,stdio輸出可能會被行緩衝,所以沒有'fflush()'的代碼很可能會工作,直到OP嘗試將stdout重定向到文件。 –

1

只是dup2(current_out, 1)取代dup2(current_out, file),事情應該更好地工作。