问题描述
问:我正在尝试更新文件放置,通过使用 fopen
模式 "r+"
,读取某个字符串,并写入返回一个修改过的字符串,但它不是工作.
A:一定要先调用fseek
你写,既要找回您正在尝试的字符串的开头覆盖,并且因为 fseek
或 fflush
之间总是需要的在读/写中读和写+"模式.
A: Be sure to call fseek
before you write, both to seek back to the beginning of the string you're trying to overwrite, and because an fseek
or fflush
is always required between reading and writing in the read/write "+" modes.
我的问题是为什么 fseek
或 fflush
在读/写+"模式下的读和写之间总是需要的?第 5.2 节安德鲁·科尼格C 陷阱和陷阱 (1989) 提到它是因为向后兼容性问题.谁能详细解释一下?
My question is why fseek
or fflush
is always required between reading and writing in the read/write "+" modes? Section 5.2 ofAndrew Koenig'sC Traps and Pitfalls (1989) mentioned that it is because of a backward compatibility issue. Can anyone explain in detail?
推荐答案
库缓冲输入和输出操作.查看该函数的 setvbuf()
和 _IOFBF
、_IOLBF
参数.
The library buffers input and output operations. Check out setvbuf()
and the _IOFBF
, _IOLBF
parameters to that funktion.
fseek()
或 fflush()
需要库来提交缓冲操作.
fseek()
or fflush()
require the library to commit buffered operations.
该标准规定了一个seek或flush操作是强制性的,以允许库有一些快捷方式;否则,对于每个 I/O 操作,lib 必须检查前一个操作是否也是读操作(或写操作),如果 I/O 的方向"发生变化,则自行触发刷新.按照原样的规范,库可能会假设客户端在更改 I/O 方向之前执行了查找/刷新.
The standard specifies a seek or flush operation as mandatory to allow the library some shortcuts; otherwise, for every I/O operation, the lib would have to check if the previous operation was also a read op (or a write op), and trigger a flush by itself if the "direction" of the I/O changed. With the specifications as-is, the library may assume the client did the seek / flush before changing I/O direction.
这篇关于为什么在更新模式下读取和写入之间总是需要 fseek 或 fflush?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!