fstream delete N bytes from the end of a binary file

c++, fstream

Solution

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.

Problem

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.

Original source

Related problems