重新路由stdin和stdout从C [英] Rerouting stdin and stdout from C
问题描述
我要重新打开标准输入
和标准输出
(也许标准错误
,而我在它)的文件句柄,这样就未来的printf()调用
或的putchar()
或看跌期权()
会去到一个文件,以及 GETC()
键,这样将来自文件中。
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)我不想永久失去标准输入/输出/错误。我想在以后重用它们在程序中。
1) I don't want to permanently lose standard input/output/error. I may want to reuse them later in the program.
2)我不想打开新的文件句柄,因为这些文件句柄将不得不周围有很多或全局(战栗地或者通过)。
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)我不希望使用任何的open()
或叉()
或其他系统 - 相关的函数,如果我不能帮助它。
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");
和,如果是这样,我怎么能获得标准输入
的原始值回来?我必须将它存储在 FILE *
和刚拿回来以后呢?
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?
推荐答案
为什么要使用 则freopen()
?该C89规格有在尾注的部分之一的答案上<&stdio.h中GT;
:
116。主要使用在 则freopen
的功能是改变与标准相关的文件
文本流( 标准错误
标准输入
或 标准输出
),因为这些标识符需要不
修改左值到的值
通过在 的fopen
函数返回
可被分配
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
普遍滥用,例如标准输入= freopen函数(newin,R,标准输入);
。这是不超过 FCLOSE(标准输入)更便携;标准输入= FOPEN(newin,R);
。这两个前pressions试图将分配给标准输入
,这是不保证分配。
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.
正确的方法使用则freopen
被省略赋值:则freopen(newin,R,标准输入);
The right way to use freopen
is to omit the assignment: freopen("newin", "r", stdin);
这篇关于重新路由stdin和stdout从C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!