Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site ms.UUCP Path: utzoo!utcsri!utai!ms!mts From: mts@ms.UUCP (Martin Stanley) Newsgroups: net.unix-wizards Subject: Re: Re: truncating a file opened via open() Message-ID: <138@ms.UUCP> Date: Sun, 23-Jun-85 23:23:59 EDT Article-I.D.: ms.138 Posted: Sun Jun 23 23:23:59 1985 Date-Received: Mon, 24-Jun-85 01:42:02 EDT References: <340@cmu-cs-edu1.ARPA> <786@turtlevax.UUCP> <217@luke.UUCP> <2315@sun.uucp> <126@maynard.UUCP> Organization: Home Computer of Martin Stanley, Toronto, Ontario Lines: 56 > > > >In article <340@cmu-cs-edu1.ARPA> hua@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@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@toronto ARPANET: mts.toronto@csnet-relay