Problem with ifstream

Started by
3 comments, last by hehenoobhehe 20 years, 5 months ago
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?
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.
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.
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]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.
"Computer games don't affect kids; I mean if Pac-Man affected us as kids, we'd all be running around in darkened rooms, munching magic pills and listening to repetitive electronic music." - Kristian Wilson, Nintendo, Inc, 1989

This topic is closed to new replies.

Advertisement