Reputation: 51
How would you add a word to a pre-existing string in a text file. I am using this in an instance that requires me to "mark" a certain line of text in this file and I want to do something like:
DELETED: data, string, text that is no longer relevant.
This question is not how do I append an existing file, but rather a specific line inside of the file.
Upvotes: 0
Views: 243
Reputation: 54325
The first and most commonly used option is to copy the file. In the copy, add the DELETED marker wherever you want it. Then when you are done, you can rename the copy to the old name, replacing it. This is a bit wasteful because you may as well have just removed the line from the copy.
A second option is to overwrite the line with comment markers. I've seen this done in very large text files. You want to open the file with a read/write fstream
, not a ifstream
and not a ofstream
. Before reading each line save the stream position. Use tellg
. Then read a line. If it was the line you wanted to find, set your output position with seekp
and write "#", or whatever the comment markers are until the end of the line. Do not overwrite the previous newline or the end newline.
Then your file would look like
data, string, text
##################
data, string, text
I think single character comment marks are better unless you can guarantee that every line will have enough room to overwrite with DELETED: at the front.
Instead of comments you could use spaces. Whatever will work with the program that reads this file.
Upvotes: 1
Reputation: 1974
Files are just streams of bytes in C++. You can't just add something in the middle, you have to shift all the content following the place of insertion, effectively rewriting the entire file.
Upvotes: 1