[C++, STL] Reusing an fstream object

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

Recommended Posts

I'm having a strange problem... simplified here to show I/O parts only.
class MyClass
{
fstream file;
};

{
if(file.is_open())
{
file.close();
}

file.open(path);
if(file.fail())
{
OH NO!!!
}
}

When I call loadFile a 2nd time on the same MyClass instance,with the same path, opening the file fails. I checked and file.close() IS being called as expected. What could be causing it?

Share on other sites
My guess is there's a race condition between the closing and reopening of the file. If you wait a little while before opening, or if you make repeated attempts, then you'll probably acquire the stream. If you know you're reopening a file then you could just not close it and seek the get pointer back to the start.

Share on other sites
Most likely the eof and fail bit are set when you are done with the input. You can clear those error bits... or just use a new fresh filestream.

Share on other sites
Quote:
 Original post by dmatterMy guess is there's a race condition between the closing and reopening of the file. If you wait a little while before opening, or if you make repeated attempts, then you'll probably acquire the stream. If you know you're reopening a file then you could just not close it and seek the get pointer back to the start.

The file isn't always the same path, that's just what I was testing... when the user selects to open a file we first close the old one as part of the opening process.

Share on other sites
Roughlty speaking, you don't. Closing and then reopening a file doesn't reset all of the necessary flags, so if the fail() was true before reusing, it will still be true. There use to be a C++ faq lite entry on this, but I can't seem to find it.

Share on other sites
Ah, I didn't consider those bits would remain set. I figured calling open() would reset them. Will try that, sounds logical.

Share on other sites
Quote:
 Original post by d000hgAh, I didn't consider those bits would remain set. I figured calling open() would reset them.
I have no idea why it doesn't reset them - it definitely should [smile]

Share on other sites
I strongly recommend not attempting to reuse the stream object, and in fact not keeping it as a data member, but just using a local variable where needed. What are you hoping to accomplish otherwise? Why would you need to keep the stream open between loadFile calls? (Do you even need to remember a file name?)

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 9
• 26
• 10
• 11
• 9
• Forum Statistics

• Total Topics
633717
• Total Posts
3013514
×