Archived

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

Problem with ifstream

This topic is 5142 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
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
Clear your flags.

ifs.clear();


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]


[edited by - Fruny on November 13, 2003 2:39:20 AM]

Share this post


Link to post
Share on other sites