为什么在更新模式下读取和写入之间总是需要 fseek 或 fflush? [英] Why is fseek or fflush always required between reading and writing in the update modes?

查看:22
本文介绍了为什么在更新模式下读取和写入之间总是需要 fseek 或 fflush?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问:我正在尝试更新文件放置,通过使用 fopen 模式 "r+",读取某个字符串,并写入返回一个修改过的字符串,但它不是工作.

Q: I'm trying to update a file in place, by using fopen mode "r+", reading a certain string, and writing back a modified string, but it's not working.

A:一定要先调用fseek你写,既要找回您正在尝试的字符串的开头覆盖,并且因为 fseekfflush 之间总是需要的在读/写中读和写+"模式.

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.

我的问题是为什么 fseekfflush 在读/写+"模式下的读和写之间总是需要的?第 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 of Andrew Koenig's C 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆