C++ : search and replace char in file

Started by
4 comments, last by CrazyCdn 18 years ago
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
Advertisement
Quote:Original post by Alessandro
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 ?
If 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.

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.

"Those who would give up essential liberty to purchase a little temporary safety deserve neither liberty nor safety." --Benjamin Franklin

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.
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.
@Boder: good point, didn't even think of that.

"Those who would give up essential liberty to purchase a little temporary safety deserve neither liberty nor safety." --Benjamin Franklin

This topic is closed to new replies.

Advertisement