Fog Creek Software
Discussion Board




How to truncate a file under DOS/Windows?

In Unix, there is a C function: truncate (const char *file, size_t length) which calls a system function and truncates the file to the desired size.

However, the program doesn't compile in VC++ since the truncate() function is not defined in any lib/dll supplied by VC++/Windows. Any other way to truncate a file?

The program compiles under Cygwin for Windows. But I don't have the source for the .lib supplied by cygwin.

Bob
Friday, February 27, 2004

SetEndOfFile()

Joel Spolsky
Fog Creek Software
Friday, February 27, 2004

That'll be two dollaz please

Joel Spolsky
Fog Creek Software
Friday, February 27, 2004

> I don't have the source for the .lib supplied by cygwin

It should be available, they're pretty fanatical about that (it is all GPL'd).


Friday, February 27, 2004

1. Install Cygwin
2. Start up a bash shell.
3. Type >myfile.

Casey Marshall
Friday, February 27, 2004

In code (sorry).

Something like:

open(filename, O_WRONLY | O_TRUNC);

Casey Marshall
Friday, February 27, 2004

I had to do this once. SetEndOfFile doesn't do all that truncate does - first you have to get a handle to the file with write access using CreateFile, and then move to the desired offset using SetFilePointer, call SetEndOfFile, and then close the handle. I always wondered if there was a less complicated way.

as
Sunday, February 29, 2004

Write zero bytes to file (Int 21h func 40h).
File is either truncated or extended to the current file position.
Note that from C you may need to use either write or _write to get this to work.

Peter Ibbotson
Tuesday, March 02, 2004

*  Recent Topics

*  Fog Creek Home