How do you truncate a file?

Tim Campbell campbell at dev8j.mdcbbs.com
Thu May 9 23:07:25 AEST 1991


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.
> : >
> : >#include <stdio.h>
> : >main () {
> : >int	i;
> : >for (i=0; i < 90 ; i++) {
> : >		(void) putchar(getchar());
> : 
> : Do you think you could have thought of a *slower* way to do this???
> 
> Could you then post the *faster* way?
> 
> 
> 
> 	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.

	-Tim

  ---------------------------------------------------------------------------
	  In real life:  Tim Campbell - Electronic Data Systems Corp.
     Usenet:  campbell at dev8.mdcbbs.com   @ McDonnell Douglas M&E - Cypress, CA
       also:  tcampbel at einstein.eds.com  @ EDS - Troy, MI
 CompuServe:  71631,654	 	 (alias  71631.654 at compuserve.com)
 P.S.  If anyone asks, just remember, you never saw any of this.



More information about the Comp.lang.c mailing list