If you want to truncate the file to zero size, you can fopen
with the "w"
flag:
FILE *fh = fopen("file.txt","w");
if (fh != NULL) fclose(fh);
For truncating to a specific size in standard C, you can do this with a transfer/rename solution, something like:
FILE *finp = fopen ("inp.txt", "rb"); // should check for NULLs
FILE *fout = fopen ("out.txt", "wb");
size_t sz = 100000; // 100,000 bytes
char *buff = malloc (sz); // should check for NULL
sz = fread (buff, 1, sz, fin); // should check for errors
fwrite (buff, 1, sz, fout);
free (buff);
fclose (fin);
fclose (fout);
rename ("out.txt", "inp.txt); // should check for error
Of course, if you have access to the Win32 headers and libraries (and I believe MinGW gives you this), you can use SetEndOfFile()
, since it does it in place, rather than having to create a new file and then rename it.
That means using Windows handle-based file I/O rather than the C FILE*
-based but, if you're limiting yourself to Windows anyway, that may not matter. If you want portability on the other hand, you'll need a solution based on standard C, such as the transfer/rename solution above.