C++ : search and replace char in file
Hi, once i open a text file using C++, which is the easiest method for searching a replacing a char, and saving the file again ?
Thanks
Quote:Original post by AlessandroIf you're actually just replacing a single character with another single character, it should be easy. One option would be to read the file into a std::string, replace the character, then write it back out to the file. For the replacing part, you could do it manually, use std::string's find() functions, use a std algorithm, or perhaps use something from boost's string algorithm library.
Hi, once i open a text file using C++, which is the easiest method for searching a replacing a char, and saving the file again ?
There's probably a way to perform the operation on the file itself, but I imagine it would be faster to do it in memory and then write the file out all at once.
If you're overwriting the original file you basically have to read it into memory, wipe it and write it back out with the changes you want.
Actually in this case you can just overwrite the characters you need to without having to read in the whole file because you can guarantee the size is constant.
Open the file for reading and writing, loop thru reading chars one at a time, then seek to write to the location of the char you want to replace.
Open the file for reading and writing, loop thru reading chars one at a time, then seek to write to the location of the char you want to replace.
If we are talking one char only (finding one char and replacing it with another) I believe you can do the replacement without streaming the file data into a string, I would believe it would be faster, so in performance-critical applications you might try to do it directly.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement