[comp.unix.questions] a portable way to truncate an open file

rjk@sawmill.UUCP (Richard Kuhns) (05/11/89)

I've got the strong feeling that this is something that should be
obvious and straight-forward, but for the life of me I can't think
of a *portable* way to do it.

The scenario:  I have a process which should only be run by one person
at a time.  I also want to record the progress of this process in a
datafile with a name that is constant across all invocations of this
process (I don't want to use a different name a la mktemp(3C) each
time).  I'd like to do the following:

	open the file (for writing);
	try to lock the file exclusively;
	if (I can't)
	    tell user someone else is running this program;
	    exit;
	endif
	truncate the file (size 0);	<--- how do I do this?
	start writing;

Under BSD, I can [f]truncate() it, but I can't think of a good way
to do it under System V, and the code has to run there too.  I can't
do the truncate as part of the [f]open(), since I don't have the lock
yet.

This sounds like it could be useful for people other than myself, so
feel free to post responces (unless you REALLY enjoy sending mail...;-)).

TIA

Rich Kuhns
pur-phy!sawmill!rjk

tjo@Fulcrum.BT.CO.UK (Tim Oldham) (05/12/89)

In article <268@sawmill.UUCP> rjk@sawmill.UUCP (Richard Kuhns) writes:
>
>I've got the strong feeling that this is something that should be
>obvious and straight-forward, but for the life of me I can't think
>of a *portable* way to do it.
>
>Under BSD, I can [f]truncate() it, but I can't think of a good way
>to do it under System V, and the code has to run there too.  I can't
>do the truncate as part of the [f]open(), since I don't have the lock
>yet.

creat(filename, mode). If the file exists, it will be truncated. It's
a while since I used BSD, but I seem to remember this is how I did it
before I knew of truncate(2)'s existence, and it's fine on sysV. 
The mode and owner are left unchanged if the file exists, so no
problems there.

Of course, you'll have to close the file if you use the algorithm
you posted, as you've opened it previously, and you hardly want to file
descriptors. But I'd change the algorithm, anyway - what's the point
opening the file before you're ready to write to it?

	Tim.

-- 
Tim Oldham      ...!mcvax!ukc!axion!fulcrum!tjo  or  tjo@fulcrum.bt.co.uk
#include	<stdisclaim>
Why have coffee, when caffeine tastes this good?