简体   繁体   English

C中的输出重定向

[英]Output redirection in C

I'm trying to redirect output in C ( ./a.out > out.log ), I want printf to print to the file instead of stdout, for some reason I couldn't achieve that, I also can't understand what 'copy' means in dup2 description in the linux manual: 我正在尝试重定向C( ./a.out > out.log )中的输出,我希望将printf打印到文件而不是stdout,由于某些原因我无法实现,我也无法理解'copy'在linux手册的dup2描述中表示:

dup2() makes newfd be the copy of oldfd, closing newfd first if necessary dup2()使newfd成为oldfd的副本,必要时先关闭newfd

Is copy means redirect? 复制意味着重定向吗?

Thanks for your help. 谢谢你的帮助。

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

int main(){
  FILE *fout=fopen("out.log","wt");
  if(!fout)
    return 1;

  printf("Hi stdout\n");

  if(dup2(fileno(fout),fileno(stdout) == -1)) return 1;

  printf("Hi file\n");

  fclose(fout);

  return 0;
}

Yes, this is a means of redirection. 是的,这是一种重定向方法。 Your code would work otherwise, except for the typo: 您的代码可以正常工作,但错字除外:

You're dupping to fd numbered fileno(stdout) == -1 ; 您正在将fd编号为fileno(stdout) == -1 ; since stdout is initially opened to file descriptor 1 , the comparison is 1 == -1 which is false; 由于stdout最初是向文件描述符1打开的,因此比较为1 == -1 ,它为false; ie 0 and you end up dup2ing your new file descriptor over standard input instead of standard output. 0 ,您最终将新文件描述符复制到标准输入而不是标准输出上。

Obviously the code should have been: 显然,代码应该是:

// notice the parentheses here      v
if (dup2(fileno(fout),fileno(stdout)) == -1) return 1;

Addendum, you probably would want to fflush the stdout before dupping, just to be sure - because the stdout might not be line buffered. 附录,你可能会想fflush dupping,只是要确定前的标准输出-因为标准输出可能无法行缓冲。

It is more portable to use the freopen to reopen stdout , but this will redirect only output from stdio functions, not the output from unix system calls or subprocesses. 使用freopen重新打开stdout更加可移植,但这将仅重定向stdio函数的输出,而不重定向unix系统调用或子进程的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM