Truncating an open file under BSD 4.3

Chris Torek chris at mimsy.UUCP
Wed Jul 27 06:27:35 AEST 1988


In article <1392 at valhalla.ee.rochester.edu> badri at valhalla.ee.rochester.edu
(Badri Lokanathan) writes:
>What is the best way to empty an already open write-only file under BSD 4.3?
>... I tried truncate but it leaves holes in the file, which make
>it unreadable.

You were on the right track.  truncate (or better, ftruncate) does not
`leave holes in the file'; rather, the sequence

	open
	seek
	write

`leave(s) holes in the file'.  Likewise, the sequence

	open
	write (moves seek pointer)
	ftruncate
	write

will create holes, since the second `write' is not at the beginning
of the file.  Hence the proper sequence is

	(void) ftruncate(fd, 0L);
	(void) lseek(fd, 0L, 0);
	/* in either order */

or (if using stdio)

	(void) fflush(fp);
	(void) fseek(fp, 0L, 0);
	(void) ftruncate(fileno(fp), 0L);
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.questions mailing list