我正在尝试在 C 中重定向输出 (./a.out > out.log
),我希望 printf 打印到文件而不是 stdout,出于某种原因我不能实现这一点,我也无法理解 linux 手册中 dup2
描述中“复制”的含义:
dup2() makes newfd be the copy of oldfd, closing newfd first if necessary
复制是否意味着重定向?
感谢您的帮助。
#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;
}
最佳答案
是的,这是一种重定向的方式。您的代码将以其他方式工作,除了拼写错误:
你正在复制到编号为 fileno(stdout) == -1
的 fd;因为 stdout
最初打开文件描述符 1
,所以比较结果是 1 == -1
,这是错误的;即 0
并且您最终通过标准输入而不是标准输出来复制您的新文件描述符。
显然代码应该是:
// notice the parentheses here v
if (dup2(fileno(fout),fileno(stdout)) == -1) return 1;
附录,您可能希望在复制之前fflush
stdout,只是为了确定 - 因为 stdout 可能没有行缓冲。
使用 freopen
更便携重新打开 stdout
,但这只会重定向 stdio 函数的输出,而不是 unix 系统调用或子进程的输出。
关于c - C中的输出重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42316795/