5

Is it possible to delete N bytes from the end of a binary file in C++ using fstream (or something similar)? I don´t want to read the whole file, cut it and write it again, but since it´s from the end of a file it seems like it shouldn't be such a problem.

Silicomancer
  • 8,604
  • 10
  • 63
  • 130
hynner
  • 1,352
  • 1
  • 11
  • 20
  • [How to remove X bytes from the end of a large file without reading the whole file?](http://stackoverflow.com/q/7392444/995714) – phuclv Aug 04 '15 at 12:47
  • [How to truncate a file in C?](https://stackoverflow.com/q/873454/995714) – phuclv Jan 07 '19 at 01:30

3 Answers3

8

I'm not aware of a generic C++ (platform independent) way to do this without writing a new file. However, on POSIX systems (Linux, etc.) you can use the ftruncate() function. On Windows, you can use SetEndOfFile().

This also means you'll need to open the file using the native functions instead of fstream since you need the native descriptor/handle for those functions.

EDIT: If you are able to use the Boost library, it has a resize_file() function in its Filesystem library which would do what you want.

TypeIA
  • 16,916
  • 1
  • 38
  • 52
4

Update:

Now in C++17 you can use resize_file from filesystem

Live on Coliru

Hani Shams
  • 331
  • 3
  • 5
0

In case you want to use Qt, QFile also provides two resize() methods that allow to truncate a file.

Silicomancer
  • 8,604
  • 10
  • 63
  • 130