fstream - shrinking file

528 views Asked by At

How can I cut the unnecesary space left at the end of the file with fstream? I've got a binary file ~250mb big and after certain operations I'm left with ~100mb of data left in file (at the beginning). The file however is still 250mb. How can I free up the disk space?

It's a lot of identical structs written to the file sequentially using:

fstream::write((char *)data_struct,sizeof(data_struct));

Sometimes the structs at the end of the file are no longer needed.

1

There are 1 answers

0
Andy Brown On BEST ANSWER

File streams don't support truncation except when being opened. You'll need to close it and then use an OS specific method to set the precise length. For Windows and Linux that is:

Windows: SetEndOfFile()

Linux: truncate()/ftruncate()