Jump to content
  • Advertisement
Sign in to follow this  
Sfpiano

C++ - Possible to replace a single line in a file?

This topic is 3984 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

I have a filetype where the first line lists the number of entries in the file. So as I append entries I need to update the number. I was wondering if there was a way to just change that first line, or do I have to keep track of the entire file and write everything out at the end?

Share this post


Link to post
Share on other sites
Advertisement
Well, anything is possible.

It's just a matter of efficiency.

If your change has the same number of characters as the line you're replacing, then it's called in-place replacement, and can be done, obviously, in place. Open file, seek location, write bytes, close file.

If the number of bytes in your change is not exactly the same, then you need to do some relocations. There's several ways, depends on the size of the file.

For files up to several megabytes, load entire file into memory. Then write all the bytes before where the change starts, append the changed bytes, then append the rest of the file.

If the file is too big, then you'll need to do the same, but by working in smaller chunks, and appending on the go.

Generally, if it's a text file, in-place replacements can be annoying, since you have no guaranteed mapping between contents and their location in file. If you insist on doing something like this, enter your number of entries as fixed width number: 00000018. Then, when you update, just change the first 8 bytes of the file.

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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!