Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fstream delete N bytes from the end of a binary file

Tags:

c++

fstream

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.

like image 550
hynner Avatar asked Feb 03 '14 14:02

hynner


2 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.

like image 102
TypeIA Avatar answered Oct 24 '22 02:10

TypeIA


Update:

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

Live on Coliru

like image 40
Hani Shams Avatar answered Oct 24 '22 03:10

Hani Shams