How do you truncate a file?

Lloyd Kremer kremer at tulip.cs.odu.edu
Mon May 13 23:52:02 AEST 1991


In article <1991May9.130725.1 at dev8j.mdcbbs.com> campbell at dev8j.mdcbbs.com (Tim Campbell) writes:
>
>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.


If you're running DOS, there is an "official" method to truncate files
in-place.  You open a file handle to the existing file, seek to the intended
point of truncation, and perform a zero-length write.

Caveat: Most C Compilers don't implement this in their write() function.
You must use the real *DOS* function call, "write to open file handle," or
whatever it's called.  DOS C compilers provide a function like intdos() or
bdos() to access DOS functions directly, calling them with the right register
settings.  I think it's DOS function 3D or 3E or around there (I don't have my
DOS Technical Reference here).

Since this is the legitimate method in DOS, it takes care of the directory
entry and FAT automatically.

P.S.  This whole issue is not a C Language question; it's entirely an
operating system concern.
-- 

					Lloyd Kremer
					Hilton Systems, Inc.
					Hampton, Virginia 23666



More information about the Comp.lang.c mailing list