Jump to content
  • Advertisement
Sign in to follow this  
tibberous1

Not able to write to a file after you read from it?

This topic is 3914 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 am trying to read down to a certain line in a file, see what it says, and then write out a new value based on that. I am using the fstream class, and setting the fstream::in | fstream::out option when I open the file, but it won't let me write to the file after reading it seems (if I write first it works fine). My plan is to just read the whole file into memory, then write the whole file back out, but I was wondering if there was a different way to do it. Thanks

Share this post


Link to post
Share on other sites
Advertisement
You can't insert into the middle of a file, nor can you overwrite using fstream. Plan accordingly.

Share this post


Link to post
Share on other sites
Quote:
Original post by tibberous1
I am trying to read down to a certain line in a file, see what it says, and then write out a new value based on that. I am using the fstream class, and setting the fstream::in | fstream::out option when I open the file, but it won't let me write to the file after reading it seems (if I write first it works fine). My plan is to just read the whole file into memory, then write the whole file back out, but I was wondering if there was a different way to do it.

Thanks


That's the usual basic approach, but you don't have to hold on to the data at once. Become familiar with the concept of a stream.

Usually you end up with something more like:


Open a blank output file in addition to the input file.
For each line in the input file:
If it's the one we're interested in:
Do awesome calculations
Output new value to the output file
Else:
Output the line to the output file
Use OS functionality to copy the output file over the input (in C++, <cstdlib> has the stuff you need)


This has the added benefit of making it easier to recover, in general, from problems that come up during the processing.

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!