when to fflush ?

Steve Summit scs at adam.mit.edu
Wed Jun 19 00:55:13 AEST 1991


In article <766 at taumet.com> steve at 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 at adam.mit.edu



More information about the Comp.lang.c mailing list