我可以在没有初始 fseek() 的情况下从头读取以追加模式打开的文件吗?

Can I read from the beginning a file open for append mode without an initial fseek()?

fopen()"a+""ab+" 模式下成功打开现有的非空文件时,我应该能够从中读取或写入末尾而无需初始调用 fseek()rewind()。 C 标准是否指定从该文件的初始读取将从文件的开头读取,或者我应该始终在读取之前设置文件位置?

C 标准似乎含糊不清,因为它在 7.21.5.2 fopen 函数 中指出:

6. Opening a file with append mode (a as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to the fseek function. In some implementations, opening a binary file with append mode (b as the second or third character in the above list of mode argument values) may initially position the file position indicator for the stream beyond the last data written, because of null character padding.

在那些文件位置指示器指向或超出最后写入数据的系统上,初始读取操作会失败吗?

行为是实现定义的:

7.21.3 Files

1 A stream is associated with an external file (which may be a physical device) by opening a file, which may involve creating a new file. Creating an existing file causes its former contents to be discarded, if necessary. If a file can support positioning requests (such as a disk file, as opposed to a terminal), then a file position indicator associated with the stream is positioned at the start (character number zero) of the file, unless the file is opened with append mode in which case it is implementation-defined whether the file position indicator is initially positioned at the beginning or the end of the file. The file position indicator is maintained by subsequent reads, writes, and positioning requests, to facilitate an orderly progression through the file.

因此,在初始读取从为更新而打开的文件 mode/write 的开头到结尾的初始读取之前,需要调用 rewind()fseek(fp, 0L, SEEK_SET),这由模式字符串确定以 "a+""ab+".

开头