如何临时将标准输出重定向到 C 程序中的文件? [英] How could I temporary redirect stdout to a file in a C program?
问题描述
在我的 C 程序中,我想暂时将标准输出重定向到 /dev/null
(例如).然后,写入 /dev/null
后,我想恢复标准输出.我该如何管理?
Within my C program, I’d like to temporarly redirect stdout to /dev/null
(for example). Then,
after writing to /dev/null
, I’d like to restore stdout. How do I manage this?
推荐答案
在 POSIX 系统上,你可以这样做:
On POSIX systems, you can do it as follows:
int bak, new;
fflush(stdout);
bak = dup(1);
new = open("/dev/null", O_WRONLY);
dup2(new, 1);
close(new);
/* your code here ... */
fflush(stdout);
dup2(bak, 1);
close(bak);
你想要的东西在一般情况下是不可能的.
What you want is not possible in further generality.
任何使用 freopen
的解决方案都是错误的,因为它不允许您恢复原始的 stdout
.通过分配给 stdout
的任何解决方案都是错误的,因为 stdout
不是左值(它是一个扩展为 FILE *
类型的表达式的宏).
Any solution using freopen
is wrong, as it does not allow you to restore the original stdout
. Any solution by assignment to stdout
is wrong, as stdout
is not an lvalue (it's a macro that expands to an expression of type FILE *
).
这篇关于如何临时将标准输出重定向到 C 程序中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!