Removing text from a file with <fstream>?

Hi,

I am trying to remove text from a .txt file, but I can't seem to find a way to do so. The way I'm currently 'removing' parts of the text is:

1) Store the file in a vector (in a specific, useful way of course).
2) Erase the vector element(s) containing the data I want to remove.
3) Create a file called "[filename]2.txt" and write the vector data to it.
4) When done writing, rename "[filename]2.txt" to "[filename].txt".

Surely there must be a better (more efficient) way to do this.. right? Or is this how file editing usually works?

Thanks.
Last edited on
That's ok, but of course, it's limited to a file that's small enough to fit in memory.

You could create the second file on the fly by reading sections of the source file and selectively writing to the second file.

You're generally on the right track. The problem is that most file systems won't let you shrink a file. That means you can't edit them in place unless the size doesn't shrink.
Yes I figured it would give memory problems with big/huge files. My program won't have to handle such files but still.. it's good to write code that can handle both.

The selectively writing is a good idea, first storing the data in a vector is indeed an unnecessary step now I think about it.

So this is a common way to 'edit' files? Or are there methods to directly edit a file, including deleting parts, and if so: is it possible to give an example or some explanation or 'names' (so I can look it up)?

Thanks again.
With the "load in memory" approach (which I like), you can entirely avoid the other file. Just rewrite the original file with the new data.

If you use a deque with the proper allocator, you can easily use the "load in memory" method.

The other method is to open the source, open the temporary, and read/modify/write from source to temporary. When done, replace the source with the temporary as you have done. This is more convenient for streaming data.
The writing to a second file first is because I want to have a backup file, for example in case the PC crashes while the program is writing. Losing the data would be quite a problem.

I went with the writing to the second file without storing information in the vector and it works fine, so.. solved!
Topic archived. No new replies allowed.