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

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

问题描述


Q:我试图通过使用 fopen mode 来更新
位置的文件。 r +

阅读某个字符串,并写入
返回一个修改过的字符串,但不是
正在工作。



A:在编写
之前,一定要调用 fseek ,这两个函数都要返回字符串开头的
尝试
来覆盖,而因为 fseek
fflush 总是需要的在
阅读和写入
+模式之间。

My问题是为什么 fseek fflush 写+模式?
的第5.2节Andrew Koenig的
C Traps and Pitfalls ( 1989)提到,这是因为一个向后兼容性问题。任何人都可以详细解释一下吗?

解决方案

缓冲区输入和输出操作。查看setvbuf()和_IOFBF,_IOLBF参数。 fseek()或fflush()要求库提交缓冲操作。该标准指定一个搜索或刷新操作是强制性的,以允许图书馆的一些捷径;否则,对于每个I / O操作,lib将必须检查前面的操作是否也是读操作(或写操作),并且如果I / O的方向改变,则自己触发刷新。 / p>

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: 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.

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?

解决方案

The library buffers input and output operations. Check out setvbuf() and the _IOFBF, _IOLBF parameters to that funktion. fseek() or fflush() require the library to commit buffered operations. 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.

这篇关于为什么在更新模式下,在读和写之间总是需要fseek或fflush?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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