truncating a file opened via open()

Guy Harris guy at sun.uucp
Thu Jun 27 15:51:40 AEST 1985


> 	In order to properly simulate the ftruncate() call from 4.2 BSD, 
> you must leave the file open in the same mode it was originally opened in.
> In order to copy, link, etc. the file you need to fclose() it...

Huh?  You only have to "fclose" it if you don't have enough file descriptors
or if, as you mention, the FD wasn't open for reading and writing.

I also don't understand why so much is made of links.  You don't have to
unlink the file unless you don't have write permission on it; if you have
write permission, a "creat" will do the truncation to zero length quite
well.  (If you have to do the "unlink" and don't have write permission on
the containing directory, you're out of luck.)

All this is slightly beside the point, as the guy wasn't asking for an
"ftruncate()" routine for non-4.2BSD systems, he was just asking for a way
to truncate a file to a particular length.  In some cases (such as in the
F77 support library, which is where both the two-copy scheme and, I believe,
the motivation of "(f)truncate" came from) you know what mode the file was
opened in.

Furthermore, given how slow "ftruncate" are, it's probably best to rewrite
the code to use some other technique, if possible, rather than to simulate
"ftruncate" by brute force.

Then again, since "ftruncate" is useful and can't be nicely built out of
other operations (it can be built out of other operations but the result is
not pretty), it should probably become a part of standard UNIX.  (Remember
V6, the UNIX that stored the seek pointer for a file in the kernel and
didn't let a program get the value, no matter now politely it asked?  "tell"
was added to V6, and the V7 "lseek" returned the seek pointer, so that you
didn't have to use a kludge like counting all the characters you wrote -
which also didn't always work, since you didn't necessarily know where the
seek pointer was then the program started.)

	Guy Harris



More information about the Comp.unix.wizards mailing list