Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

c - Why is fseek or fflush always required between reading and writing in the update modes?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. With the specifications as-is, the library may assume the client did the seek / flush before changing I/O direction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...