我正在尝试使用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;
}
有帮助吗?

解决方案

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

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

其他提示

在此之前,您必须确保要确保做的一件事是致电 fflush(stdout); 切换之前 stdout 从其下方的文件描述符。可能发生的可能是C标准库正在缓冲您的输出,这并不意识到您正在其下方的文件描述符上移动。您使用的数据使用 printf() 不是 实际上 发送到基础文件描述符,直到其缓冲区已满(或您的程序从 main).

像这样插入电话:

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

在两个电话之前 dup2().

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top