C freopen descriptor - close manually/leave opened

岁酱吖の 提交于 2021-02-19 06:01:33

问题


I've been using freopen (from stdio.h) function before without asking myself this question. But now I'm unsure.

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");

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 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.


回答1:


fclose(stdout); works to close the redirect.

It is usually cleaner to close the filehandle. If a filepointer is open when a program exits, it will get closed for you.

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");

You can restore stdout to the terminal back again (and break redirects from command-line) with:

freopen("/dev/tty", "a", stdout);

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 ).



来源:https://stackoverflow.com/questions/14819575/c-freopen-descriptor-close-manually-leave-opened

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!