# 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.

## 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 on other sites
You can't insert into the middle of a file, nor can you overwrite using fstream. Plan accordingly.

##### Share on other sites
Quote:
 Original post by tibberous1I 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 fileUse 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.

1. 1
Rutin
26
2. 2
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 21
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631763
• Total Posts
3002190
×