Is setting a FILE* equal to stdout portable?

前提是你 提交于 2020-02-23 11:38:29

问题


I've got a function that needs to be able to write to either stdout, or to a file, depending on what the user wants. It defaults to standard out though. To accomplish this, I'm doing the following (minus error checking etc):

FILE* out;
if (writeToFile) { /*Code to open file*/; }

else
    out = stdout;

// ...rest of the function goes here

if (out != stdout)
    fclose(out);

This certainly does the trick, but I have no idea how portable it is. And if it's not, and/or there's another problem with it, how should I go about this?


回答1:


Yes, it's portable and it's fine, provided you don't also mess with the low-level implementation of *stdout (e.g. by calling close(fileno(stdout)) on Posix or using dup).




回答2:


It should be fine. You might have trouble if you pass the pointer back and forth across the boundary of a DLL (ie, C code outside DLL passes pointer to stdout to C code inside DLL), but apart from that it should be portable.



来源:https://stackoverflow.com/questions/12008516/is-setting-a-file-equal-to-stdout-portable

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