Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Problem with ifstream

This topic is 5303 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 want to open mulitiple files and I use the same filestream each time, opening and closing the file stream each time that I need to read a file.
ifstream ifStr;

while()
{
    ifStr.open();
    ....
    ....
    ....
    ....
    ....
    ifStr.close();
}
Problem is that I can only open one file successfully, and no matter what I do, IF I use the same file stream,(ifStr) to open the second/third/....nth file, I cant do that. The filename, path etc are fine because this does work:
ifstream ifStr1;
ifStr1.open( "filename1" );
....
....
....
....
....
ifStr1.close();

ifstream ifStr2;
ifStr2.open( "filename2" );
....
....
....
....
....
ifStr2.close();
So as I see it, I cant use the *same* file stream twice/mulitple times within the same scope, even though I do close the file each time. What am I doing wrong?

Share this post


Link to post
Share on other sites
Advertisement
first, you''re worried about one small construction cost per file open? The construction probably costs less than reading a byte from the file.

second, I''m not aware of any problems with reusing fstreams. Maybe try to create a sample program that shows the problem (we don''t want to see 10321983120 lines of your project) and post that.

Share this post


Link to post
Share on other sites
Well you should have no problem with opening and closeing multiple files with the same ifstream. If you cant get it to work maybe do something like this...

void ReadFile(char filename[20]) {
ifstream fin(filename, ios::binary);
if(!fin)
return false;
...
...
...
...
fin.close();

}

then just call your read function with the filename each time.

Share this post


Link to post
Share on other sites
actually I had this very problem once with msvc6. a workaround was to declare the ifstream object inside the while loop for it to be reconstructed each time.

Share this post


Link to post
Share on other sites

  • 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!