. 我搜索了 C11 Draft n1570 pdf 寻找任何没有运气的引用,fo-6ren">
gpt4 book ai didi

c - 以读取模式打开的流的 fputc() 行为

转载 作者:太空狗 更新时间:2023-10-29 16:56:13 28 4
gpt4 key购买 nike

当使用 fopen("/some/path", "r") 创建流时,我无法找到对 fputc() 指定行为的任何引用>.

我搜索了 C11 Draft n1570 pdf 寻找任何没有运气的引用,fopen() 函数规范讨论了将未知字符作为未定义行为的模式参数传递。但它没有说明创建的流上的后续 IO。

这是fwrite()函数规范

7.21.8.2 The fwrite function

Synopsis

  1. #include <stdio.h>
    size_t fwrite(const void * restrict ptr,
    size_t size, size_t nmemb, FILE * restrict stream);

Description

  1. The fwrite function writes, from the array pointed to by ptr, up to nmemb elements whose size is specified by size, to the stream pointed to by stream. For each object, size calls are made to the fputc function, taking the values (in order) from an array of unsigned char exactly overlaying the object. The file position indicator for the stream (if defined) is advanced by the number of characters successfully written. If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.

Returns

  1. The fwrite function returns the number of elements successfully written, which will be less than nmemb only if a write error is encountered. If size or nmemb is zero, fwrite returns zero and the state of the stream remains unchanged.

它将我们带到 fputc() 函数,所以

7.21.7.3 The fputc function

Synopsis

  1. #include <stdio.h>
    int fputc(int c, FILE *stream);

Description

  1. The fputc function writes the character specified by c (converted to an unsigned char) to the output stream pointed to by stream, at the position indicated by the associated file position indicator for the stream (if defined), and advances the indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the output stream.

Returns

  1. The fputc function returns the character written. If a write error occurs, the error indicator for the stream is set and fputc returns EOF.

如您所见,我担心的情况没有任何解释。

最佳答案

这是未定义的行为,如果不是输出流,标准没有定义行为。这是来自 4 Conformance 部分,其中说(强调我的):

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe ‘‘behavior that is undefined’’.

现在当然这不会阻止实现进一步定义行为,我们可以看到 POSIX fputc通过 EBADF 指示此错误:

[EBADF]

[CX] [Option Start] The file descriptor underlying stream is not a valid file descriptor open for writing.

注意 CX 表示对 C 标准的扩展。

关于c - 以读取模式打开的流的 fputc() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888826/

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