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.
-
How to remove X bytes from the end of a large file without reading the whole file?phuclv– phuclv2015-08-04 12:47:59 +00:00Commented Aug 4, 2015 at 12:47
-
How to truncate a file in C?phuclv– phuclv2019-01-07 01:30:32 +00:00Commented Jan 7, 2019 at 1:30
Add a comment
|
3 Answers
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.