I have a text file associated with the std::fstream object.

 std::fstream finout("text.txt"); 

Then from this file read. The read data is analyzed and some of them are deleted. Thus, the size of the output data can be reduced and it becomes necessary to truncate the file (or change its size). It seems completely silly and wasteful to create a new file and write the result into it. I would like to get a more efficient and easier way to achieve the desired result. The C language offers the functions ftruncate and chsize , however I use an object of class std::fstream .

PS On English sites I met similar questions, but I would like to know the opinion of the Russian-speaking audience.

2 answers 2

fstream does not support such operations.

You can try using std::experimental::filesystem::resize_file (c ++ 17)

Well or good old _chsize/ftruncate .

    The question is incorrectly put - if the data in the file is deleted arbitrarily, in any place - what circumcision can there be ?? To form the file again and delete the old one. However, if this is a sooo big file and it is irrational to reformat it - you can use seekp - in this case you can think of some file structure to mark the deleted pieces as empty, then, when adding data, look for suitable size empty pieces and write there - at least in the beginning , in the middle, at the end of the file ...