Truncating an open file under BSD 4.3

Guy Harris guy at gorodish.Sun.COM
Tue Jul 26 17:14:07 AEST 1988


> What is the best way to empty an already open write-only file under BSD 4.3?

If by "empty" you mean "reduce to zero length", use "ftruncate".

> I tried truncate but it leaves holes in the file, which make
> it unreadable.

You must have done it wrong.  Note that, even though "ftruncate(fd, 0L)"
truncates the file to zero length, it does NOT move the seek pointer; thus,

	write(fd, lots of data, how much data);
	...
	ftruncate(fd, 0L);
	write(fd, more data, how much more data);

will NOT put the "more data" at the beginning of the file, but will put it at
the same place it would have had the "ftruncate" not been done; this results in
a hole of size equal to the size of the file before the "ftruncate".  Do an
"lseek(fd, 0L, 0)" after the "ftruncate".

Note that if you're using standard I/O to write to the file, you probably have
to "fflush" the file before doing the "ftruncate".

> I also could not find a way with fcntl, which surprises me.

Why?  "fcntl" was originally intended to manipulate descriptors, not the
objects they referred to; subsequently, "fcntl" has turned into something
similar to "ioctl" but different (e.g., it's used for file locking - I'm not
sure what the *intended* difference between "fcntl" and "ioctl" is), but
nobody's made "fcntl" do file truncation - yet.



More information about the Comp.unix.questions mailing list