我怎么能临时重定向标准输出到一个C程序文件? [英] How could I temporary redirect stdout to a file in a C program?

查看:118
本文介绍了我怎么能临时重定向标准输出到一个C程序文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C程序,我想即暂时重定向到STDOUT一个/ dev / null的(例如)。然后
写后的/ dev / null的我想恢复STDOUT。如何管理呢?

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 是错误的,因为它不会让你恢复原来的标准输出。通过转让的任何解决方案,以标准输出是错误的,因为标准输出不是一个左值(它是扩展到一个前宏类型pression 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆