How do you truncate a file?

John J. Rushford Jr jjr at rushpc
Mon May 13 01:53:09 AEST 1991


In article <1991May9.130725.1 at dev8j.mdcbbs.com> campbell at dev8j.mdcbbs.com (Tim Campbell) writes:
>In article <792 at uswnvg.UUCP>, dfpedro at uswnvg.UUCP (Donn Pedro) writes:
>> In article <1991May6.194614.9641 at pensoft.uucp>, lwb at pensoft.uucp (Lance Bledsoe) writes:
>> : In article <f25g_zd at rpi.edu> fitz at mml0.meche.rpi.edu (Brian Fitzgerald) writes:
>> : >Rudi Cilibrasi writes:
>> : >>Suppose I have a 100-byte file called "myfile.dat", and I want to get
>> : >>rid of the last 10 bytes.
>> : >
>> 	dfpedro at uswnvg.UUCP
>-- 
>I've seen some interesting and somewhat amusing responses to this one so
>far.
>
>IF you have DOS and want this to run real fast on any file of any size and
>want it to truncate the file in place (not making a copy), then you could
>always fseek to the 10th byte from the end of the file and overwrite and EOF
>mark, then edit the directory entry in DOS to indicate that the file is now
>10 bytes smaller.  Of course you'd need to know the layout of a directory
>entry and although the code would run faster compared to this example 
>(especially on big files), it would certainly require more time to write
>the code.  I'd only write it if I needed to do this often.  Of course if
>I didn't need to do this often then I'd probably just use a text editor.
>
>I just don't know unix well enough to know a clever way to handle this 
>situation without actually copying the file.
>

In Unix the above method would wreak havoc with the filesystem if you
could use it.  You would have to update the freelist and inode entry
in the superblock or run fsck -y to fix the filesystem.  This would
prove to be difficult unless you're 'root'.


-- 

John
----
Westminster Colorado	|



More information about the Comp.lang.c mailing list