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

Behavior of fputc() for a stream opened with read mode

当使用 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 一致性部分,它说 (emphasis mine):

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 标准的扩展。