gpt4 book ai didi

c - 检查C中freopen()的返回值

转载 作者:行者123 更新时间:2023-12-02 08:36:25 25 4
gpt4 key购买 nike

我知道freopen的正确用法是忽略给定post的分配:
freopen("/dev/tty","r", stdin);
我的问题是,我还应该检查返回值吗?我要重新打开标准输入并关闭它。例如:

if(freopen("/dev/tty","r", stdin)==NULL) {
fprintf(stderr, "Unable to redirect stdin from file\n");
exit(1);
}

最佳答案

这对于freopen的documentation说:

If the file is successfully reopened, the function returns the pointer passed as parameter "stream", which can be used to identify the reopened stream. Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.



因此,可以的,您可以针对NULL检查返回值以查看是否存在错误,或者检查errno。

关于您的评论,文档说:

If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.



基于“独立于该流是否成功关闭”,如果发生错误,原始流似乎可以保持打开状态,或者处于 undefined 状态。无论如何,这不会产生任何实际的区别,因为无论如何freopen失败后,您都不希望使用该流。

关于c - 检查C中freopen()的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20908740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com