Click to See Complete Forum and Search --> : truncating a file


TekBoy
April 29th, 2002, 09:13 PM
How do I truncate a file's size using ANSI C?

The file's size is 200 bytes, I want to shrink it to 100 bytes. I know how to do this in POSIX and Win32, but is there no standard ANSI C method for accomplishing this simple task?

TekBoy

P.S. please always rate all post that help you. I will do the same....

SreeDharan
April 29th, 2002, 10:51 PM
Hi,
You can use chsize(),

#include <fcntl.h>
#include <io.h>


int main(void)
{
int handle;

handle = open("C:\\a.txt", O_RDWR);


/* truncate the file to 50 bytes in size */
chsize(handle, 50);

/* close the file */
close(handle);
return 0;
}






Regards,
Sreedharan.

Axter
April 29th, 2002, 11:34 PM
chsize() is not part of the C/C++ standards.

You can try using fseek and fflush to extend the file length.

http://www.axter.com

TekBoy
April 30th, 2002, 02:01 PM
Thanks for your help, but unfortunately chsize() is not ANSI C :-(

TekBoy

P.S. please always rate all post that help you. I will do the same....

TekBoy
April 30th, 2002, 02:05 PM
Thanks, but I would like to truncate (shrink) the file, not extend it.

TekBoy

P.S. please always rate all post that help you. I will do the same....