从 C 重新路由标准输入和标准输出 [英] Rerouting stdin and stdout from C
问题描述
我想重新打开 stdin
和 stdout
(也许还有 stderr
)文件句柄,以便将来调用printf()
或 putchar()
或 puts()
将转到一个文件,并在以后调用 getc()
code> 等将来自一个文件.
1) 我不想永久丢失标准输入/输出/错误.我可能想稍后在程序中重用它们.
2) 我不想打开新的文件句柄,因为这些文件句柄要么被大量传递,要么是全局传递(不寒而栗).
3) 如果我不能帮忙,我不想使用任何 open()
或 fork()
或其他依赖于系统的函数.>
所以基本上,这样做是否有效:
stdin = fopen("newin", "r");
而且,如果是这样,我怎样才能取回 stdin
的原始值?我是否必须将其存储在 FILE *
中,然后再取回?
为什么使用 freopen()
?C89 规范在
部分的尾注之一中给出了答案:
116.freopen
函数的主要用途是更改与标准关联的文件文本流 (stderr
,stdin
或 stdout
),因为这些标识符不需要值的可修改左值fopen
函数返回可能会被分配.
freopen
通常被误用,例如stdin = freopen("newin", "r", stdin);
.这并不比 fclose(stdin); 更便携.stdin = fopen("newin", "r");
.这两个表达式都试图分配给 stdin
,但不能保证可分配.
使用freopen
的正确方法是省略赋值:freopen("newin", "r", stdin);
I want to reopen the stdin
and stdout
(and perhaps stderr
while I'm at it) filehandles, so that future calls to printf()
or putchar()
or puts()
will go to a file, and future calls to getc()
and such will come from a file.
1) I don't want to permanently lose standard input/output/error. I may want to reuse them later in the program.
2) I don't want to open new filehandles because these filehandles would have to be either passed around a lot or global (shudder).
3) I don't want to use any open()
or fork()
or other system-dependent functions if I can't help it.
So basically, does it work to do this:
stdin = fopen("newin", "r");
And, if it does, how can I get the original value of stdin
back? Do I have to store it in a FILE *
and just get it back later?
Why use freopen()
? The C89 specification has the answer in one of the endnotes for the section on <stdio.h>
:
116. The primary use of the
freopen
function is to change the file associated with a standard text stream (stderr
,stdin
, orstdout
), as those identifiers need not be modifiable lvalues to which the value returned by thefopen
function may be assigned.
freopen
is commonly misused, e.g. stdin = freopen("newin", "r", stdin);
. This is no more portable than fclose(stdin); stdin = fopen("newin", "r");
. Both expressions attempt to assign to stdin
, which is not guaranteed to be assignable.
The right way to use freopen
is to omit the assignment: freopen("newin", "r", stdin);
这篇关于从 C 重新路由标准输入和标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!