C语言 freopen 标准输出和控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7664788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
freopen stdout and console
提问by SSight3
Given the following function:
给定以下函数:
freopen("file.txt","w",stdout);
Redirects stdout into a file, how do I make it so stdout redirects back into the console?
将 stdout 重定向到一个文件中,我如何才能使 stdout 重定向回控制台?
I will note, yes there are other questions similar to this, butthey are about linux/posix. I'm using windows.
我会注意到,是的,还有其他与此类似的问题,但它们是关于 linux/posix 的。我正在使用窗户。
You can't assigned to stdout, which nullifies one set of solutions that rely on it. dup and dup2() are not native to windows, nullifying the other set. As said, posix functions don't apply (unless you count fdopen()).
您不能分配给标准输出,这会使依赖它的一组解决方案无效。dup 和 dup2() 不是 Windows 原生的,从而使另一组无效。如上所述,posix 函数不适用(除非您计算 fdopen())。
回答by Hasturkun
You should be able to use _dupto do this
您应该能够使用它_dup来执行此操作
Something like this should work (or you may prefer the example listed in the _dupdocumentation):
这样的事情应该可以工作(或者您可能更喜欢_dup文档中列出的示例):
#include <io.h>
#include <stdio.h>
...
{
int stdout_dupfd;
FILE *temp_out;
/* duplicate stdout */
stdout_dupfd = _dup(1);
temp_out = fopen("file.txt", "w");
/* replace stdout with our output fd */
_dup2(_fileno(temp_out), 1);
/* output something... */
printf("Woot!\n");
/* flush output so it goes to our file */
fflush(stdout);
fclose(temp_out);
/* Now restore stdout */
_dup2(stdout_dupfd, 1);
_close(stdout_dupfd);
}
回答by dtyler
回答by RushPL
After posting the answer I have noticed that this is a Windows-specific question. The below still might be useful in the context of the question to other people. Windows also provides _fdopen, so mayble simply changing 0 to a proper HANDLE would modify this Linux solution to Windows.
发布答案后,我注意到这是一个特定于 Windows 的问题。以下内容在对其他人的问题的上下文中仍然可能有用。Windows 还提供了 _fdopen,因此可能只需将 0 更改为适当的 HANDLE 即可将此 Linux 解决方案修改为 Windows。
stdout = fdopen(0, "w")
stdout = fdopen(0, "w")
#include <stdio.h>
#include <stdlib.h>
int main()
{
freopen("file.txt","w",stdout);
printf("dupa1");
fclose(stdout);
stdout = fdopen(0, "w");
printf("dupa2");
return 0;
}

