6

我正在尝试使用 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;
}
4

3 回答 3

4

在此之前您必须确保做的一件事是在将文件描述符从其下fflush(stdout);切换出来之前调用。stdout可能发生的情况是 C 标准库正在缓冲您的输出,而没有意识到您正在移动它下面的文件描述符。您使用写入的数据实际上printf()不会发送到底层文件描述符,直到其缓冲区已满(或您的程序从 中返回)。main

像这样插入调用:

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

在两个调用之前dup2().

于 2011-07-24T07:54:31.120 回答
3

你的第二个dup2电话是错误的,替换为:

if (dup2(current_out, 1) < 0) {
于 2011-07-24T07:57:51.357 回答
1

只需替换dup2(current_out, file)dup2(current_out, 1),事情应该会更好。

于 2011-07-24T07:58:09.330 回答