2011-07-24 175 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),事情应该更好地工作。