C freopen描述符-手动关闭/保持打开状态 [英] C freopen descriptor - close manually/leave opened
问题描述
我一直在使用freopen(来自stdio.h)函数,而没有问自己这个问题.但是现在我不确定.
I've been using freopen (from stdio.h) function before without asking myself this question. But now I'm unsure.
例如我重新打开了stdout:
E.g. I've reopened stdout:
#define OUTPUT_FILE "out.txt"
if ( freopen(OUTPUT_FILE,"w+",stdout) == NULL)
printf("logout can't be opened\n");
通常每个进程都具有并自动处理stdout,stderr,stdin,我们不必关心它们的关闭.我已经重新打开标准输出.
我应该打电话给fclose来关闭重新打开的stdout吗?
Usually every process has and handles stdout, stderr, stdin automatically and we needn't care about closing of them.
But how is it to be here? I have reopened stdout.
Should I call fclose for closing reopened stdout?
PS我更乐于看一下执行此处理的代码部分,而不是听到我可以确信这里一切都很好.
在此先感谢您提供任何提示.
PS
I'd be gladder to look at part of code that does this handling than to hear that I can be just confident that everything is fine here.
Thanks in advance, for any tips.
推荐答案
fclose(stdout);
用于关闭重定向.
关闭文件句柄通常比较干净.如果在程序退出时打开文件指针,它会为您关闭.
It is usually cleaner to close the filehandle. If a filepointer is open when a program exits, it will get closed for you.
但是,如果您只关闭指针,stdout不会再次重定向到终端.
But, if you just close the pointer, stdout will not get redirected to the terminal again.
freopen("re.txt", "w", stdout);
printf("this is redirected stdout");
fclose(stdout);
printf("this not");
您可以使用以下方法再次将stdout恢复到终端(并从命令行中断重定向):
You can restore stdout to the terminal back again (and break redirects from command-line) with:
freopen("/dev/tty", "a", stdout);
您可以使用 dup
(示例)如果要撤消freopen( http://c-faq.com/stdio/undofreopen.html ).
You can use dup
( example ) to restore the previous pointer or don't use freopen at all, if you want to undo freopen ( http://c-faq.com/stdio/undofreopen.html ).
这篇关于C freopen描述符-手动关闭/保持打开状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!