Sign in to follow this  
d000hg

[C++, STL] Reusing an fstream object

Recommended Posts

I'm having a strange problem... simplified here to show I/O parts only.
class MyClass
{
 fstream file;
 void loadFile(const string &path);
};

void MyClass::loadFile(const string &path)
{
 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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by dmatter
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.


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 this post


Link to post
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 this post


Link to post
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?)

Share this post


Link to post
Share on other sites
Quote:
Original post by swiftcoder
There use to be a C++ faq lite entry on this, but I can't seem to find it.
I was looking on the wrong FAQ [smile]

The entry is here: http://gcc.gnu.org/onlinedocs/libstdc++/faq.html#faq.stream_reopening_fails

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this