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.

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Update:

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

Live on Coliru

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.