*BSD News Article 19246


Return to BSD News archive

Xref: sserve comp.unix.programmer:10931 comp.unix.bsd:12360 comp.unix.questions:37464
Path: sserve!newshost.anu.edu.au!munnari.oz.au!news.Hawaii.Edu!ames!agate!mania!ianb
From: ianb@mania.cea.berkeley.edu (Ian Barkley-Yeung)
Newsgroups: comp.unix.programmer,comp.unix.bsd,comp.unix.questions
Subject: Truncating file from file descriptor
Followup-To: comp.unix.programmer
Date: 6 Aug 1993 21:36:49 GMT
Organization: Center for Extreme Ultraviolet Astrophysics
Lines: 34
Message-ID: <23uith$hdj@agate.berkeley.edu>
NNTP-Posting-Host: mania.cea.berkeley.edu
Keywords: C

(All questions relate to C programming under Sun's BSD 4.3 -- SunOS 4.1.2)

Question 1:
I'm not sure if this can be done, but:

I am trying to write a C function which is passed an open file descriptor
(int iFD) and open file pointer (FILE * pfi, from fdopen) (but which is NOT
passed the file name), and which overwrites the current contents of the file
with some new contents. In general, the new contents may be shorter than the
old contents, in which case the file should be shortened. The file descriptor
should still be open when the function returns. (I'm using fcntl locks, and
I don't want to unlock the file yet).

As far as I can see, the only way to shorten a file is to truncate it,
either with the O_TRUNC flag to open() or a "w" to fopen(). But I can't find
a way to truncate a file without opening it again, and that requires the
filename. (I tried fdopen(iFD, "w") -- no dice.) 

So is there a way to truncate or otherwise shorten a file with a file
descriptor but withOUT the file name? 

Question 2:  

If I DO hack my program enough that I can pass the file name to the
function, and then do something like 
close(open(filename, O_WRONLY | O_TRUNC)); 
to truncate the file, will this cause problems for the fcntl locks? In
general, are there any gotchas I, as an fcntl lock novice, should know
about? 

Thanks muchly,
-Ian 

Followups via email to me (ianb@cea.berkeley.edu) or to comp.unix.programmer