Newsgroups: comp.lang.c Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!batcomputer!caen!zaphod.mps.ohio-state.edu!think.com!snorkelwacker.mit.edu!bloom-picayune.mit.edu!news From: scs@adam.mit.edu (Steve Summit) Subject: Re: when to fflush ? Message-ID: <1991Jun18.145513.22562@athena.mit.edu> Keywords: fflush , fseek, fwrite Sender: news@athena.mit.edu (News system) Reply-To: scs@adam.mit.edu Organization: Thermal Technologies, Cambridge, MA References: <504@bally.Bally.COM> <766@taumet.com> Distribution: usa Date: Tue, 18 Jun 91 14:55:13 GMT Lines: 37 In article <766@taumet.com> steve@taumet.com (Stephen Clamage) writes: >When you write to a stdio FILE, the data you write must go to the current >file position. If you then seek and do another write, that data must >go to the new file position. If you seek and read, the read might >involve all or part of the buffered data. This leaves the implementation >with two main choices: > >1. Always flush just before seeking. This is always correct (satisfies > all ANSI C requirements) and takes no extra bookkeeping. > >2. Keep track of where each buffered piece of data goes, and when you > can't stand it any more, write out all the pieces you have saved... Actually, there's a case Steve left out. If an fseek is "small," its target may correspond to a location already mapped into the existing stdio buffer. It is (or ought to be) a simple operation to note this case and readjust the stdio data structures without flushing the buffer or lseek(2)'ing the underlying (integer) file descriptor. This strategy is complicated, however, by the fact that: 1. An "r+" or "w+" stream may change from reading to writing around an fseek (fseek on such a stream therefore has to flush the buffer completely to allow a sane implementation, since it can't tell if the next I/O operation will reverse direction), and 2. fseek is supposed to erase any memory of ungetc'ed characters. Number 2 kills the optimization (unless you use a separate buffer for all pushback), which always seemed to me to be a bit of a shame. Steve Summit scs@adam.mit.edu