when to fflush ?

der Mouse mouse at thunder.mcrcim.mcgill.edu
Sun Jun 16 06:34:57 AEST 1991


In article <504 at bally.Bally.COM>, siva at bally.Bally.COM (Siva Chelliah) writes:

> Does seeking to the end of a file causes a flushing of the buffer ?

Possibly; this depends on the implementation and possibly many other
things you have no control over, like temporary system memory
shortages.

> Look at the following program.  Even though I write only 5 bytes,

6, actually, counting the newline.

> when you do a cat on test.out , you see "hello."

Why is this surprising?  Isn't that what you wrote?  (Actually, it's
not; you wrote a newline as the sixth character instead of a period.
I'll take that to be ignorable.)

> 	FILE *fp;
> 	char buf[80];
> 	strcpy(buf,"hello\n");
> 	system ("touch test.out");      /* just to create the file */

This isn't needed; the fopen creates it if it's not there already.
(Assuming a non-buggy system, and assuming the open succeeds - which I
notice you don't check for.)

> 	fp = fopen ("test.out","r+");
> 	fseek(fp,0L,0);         /* seek to start of file - you do not need this */
> 	fwrite(buf,strlen(buf),1,fp);
> 	fseek(fp,0L,2);                 /* seek to end of file */
> 	sleep(500);

So, on the implementations where you observe this behavior, fseek()
chooses to flush the stdio buffer.  There is nothing wrong with this;
the implementation may flush the buffer at any time it pleases.  (The
only requirement is that it must flush at certain times, such as when
you call fflush; there are no times at which it must not flush.)

					der Mouse

			old: mcgill-vision!mouse
			new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.unix.aix mailing list