truncating a file opened via open()

Martin Stanley mts at ms.UUCP
Mon Jun 24 13:23:59 AEST 1985


> > > >In article <340 at cmu-cs-edu1.ARPA> hua at cmu-cs-edu1.ARPA (Ernest Hua) writes:
> > > >>Does anyone have any idea how to truncate a file at the current point in
> > > >>writing if it is opened by open()?
> > 
> > There are precisely two solutions for non-4.2BSD systems:
> > 1) implement (f)truncate on your system...
> 
> Kind of tough for people without source licenses (I know, I'm whining).
> 
> > 2) Copy the entire file, up to the point of truncation, to a temporary file,
> > then copy it back to the original file.
> >
> > 	Guy Harris
> 
> I don't see how this works unless you unlink the file and then re-creat
> it before writing it back.  But the original question implied you only had
> a descriptor for the file, not a name...  so you can't unlink or re-creat
> it.  And even if you knew the name, other links wouldn't get truncated.
> Sounds like it's pretty tough to fake this one ...  sigh ...
> 
> - Larry Campbell
>   The Boston Software Works, Inc., 120 Fulton St., Boston MA 02109
> UUCP: {decvax, security, linus, mit-eddie}!genrad!enmasse!maynard!campbell
> ARPA: decvax!genrad!enmasse!maynard!campbell at DECWRL.ARPA

There's also another problem: 

	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 so you
will need to reopen it later. The catch is that you do not know in what
mode it was originally opened.  (Also, if the file was originally opened
in write-only mode you will not be able to read it to copy it to the
temporary, so you must fclose() the file to begin with and then
re-open for read/write). 

	I wrote a substitute ftruncate() call that takes two arguments:
the file pointer and the file name. (Instead of a file pointer and the
length desired). It truncates the file at the position of the current
file pointer. After the copy and/or re-linking, I reopen the file in
"a+" mode and hope for the best. I do not take care of multiple links
at all, since that was not necessary for my application.

	(If anyone wants my code, drop me a line and I'll send it along.
It works, but certainly can be made more efficient).
-- 

 Martin Stanley
 Department of Computer Science
 University of Toronto
 Toronto, ON
 M5S 1A4

 USENET:	{decvax,ihnp4,linus,uw-beaver}!utcsri!utai!ms!mts
 CSNET:		mts at toronto
 ARPANET:	mts.toronto at csnet-relay



More information about the Comp.unix.wizards mailing list