加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在关闭的文件上fprintf不应该失败吗?

发布时间:2020-12-16 10:14:25 所属栏目:百科 来源:网络整理
导读:请注意以下终端输出: $cat fprintf-closed-file.c#include stdio.hint main(){ FILE * ofile = fopen("/tmp/goo","w"); int success = fprintf(ofile,"Hello %sn","World!"); printf("Success: %dn",success); fclose(ofile); success = fprintf(ofile,"T
请注意以下终端输出:

$cat fprintf-closed-file.c
#include <stdio.h>
int main()
{
    FILE * ofile = fopen("/tmp/goo","w");
    int success = fprintf(ofile,"Hello %sn","World!");
    printf("Success: %dn",success);
    fclose(ofile);
    success = fprintf(ofile,"Trying again...");
    printf("Success: %dn",success);
}
$clang -o fprintf-closed-file fprintf-closed-file.c
$./fprintf-closed-file
Success: 13
Success: 15
$cat /tmp/goo
Hello World!

C11标准的第7.21.6.1节说:

The fprintf function writes output to the stream pointed to by stream,
under control of the string pointed to by format that specifies how
subsequent arguments are converted for output.

接下来是转换说明符的描述,但结尾为:

Returns

The fprintf function returns the number of characters
transmitted,or a negative value if an output or encoding error
occurred.

看来假定文件在第二次fprintf调用时关闭,它应该会失败,但事实并非如此.我在Kubuntu Trusty 64位上使用Clang 4.0.1和GCC 4.8.4对此进行了测试.

我对标准的理解是否有缺陷,还是应该提交错误?

解决方法

引用C99,7.19.3文件:

  1. […] The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams).

从而:

fclose(ofile);
success = fprintf(ofile,"Trying again...");

第二行从ofile读取,其中(在fclose之后)具有不确定的值.这有未定义的行为.

另见附件J.2:

  1. The behavior is undefined in the following circumstances:
    […]

    • The value of an object with automatic storage duration is used while it is indeterminate (6.2.4,6.7.8,6.8).

    • The value of a pointer to a FILE object is used after the associated file is closed (7.19.3).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读