设置 FILE* 是否等于 stdout 可移植? [英] Is setting a FILE* equal to stdout portable?

查看:40
本文介绍了设置 FILE* 是否等于 stdout 可移植?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数需要能够写入标准输出或文件,这取决于用户想要什么.虽然它默认为标准输出.为此,我正在执行以下操作(减去错误检查等):

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?

推荐答案

是的,它是可移植的,而且很好,前提是你不要搞乱 *stdout 的低级实现(例如通过在 Posix 上调用 close(fileno(stdout)) 或使用 dup).

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

这篇关于设置 FILE* 是否等于 stdout 可移植?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆