【问题标题】:redirecting standard output in c then resetting standard output在c中重定向标准输出然后重置标准输出
【发布时间】:2011-07-24 07:50:58
【问题描述】:

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

【问题讨论】:

标签: c fcntl unistd.h


【解决方案1】:

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

像这样插入调用:

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

在两次调用dup2()之前。

【讨论】:

  • 我不认为这是 OP 的问题,但这是一个非常好的建议,几乎总是应该在您将 stdio 与文件描述符 io 混合使用时遵循。
  • 是的,实际上我一开始并没有注意到错误的文件描述符,直到其他人提到它。写入终端时,stdio 输出可能会被行缓冲,因此没有fflush() 的代码可能会工作,直到 OP 尝试将 stdout 重定向到文件。
【解决方案2】:

您的第二个dup2 呼叫错误,替换为:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多