Jump to content
  • Advertisement
Sign in to follow this  
Alessandro

C++ : search and replace char in file

This topic is 4515 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!