Click to See Complete Forum and Search --> : loop over open file


manojg
September 28th, 2005, 11:54 AM
Hi,

I am tring to open and read a list of 10 files stored in a file name "file_list". But it can open first file only. Here is my code:

------------------------------------------------------

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

main()
{

string name;
ifstream in, in_file;

in.open("file_list");

for(int i=0; i<10; i++){
getline(in,name);
in_file.open(name.c_str());
if(in_file.fail())
cout << name << " file can't open" << endl;
else
cout << name << " ok" << endl;
in_file.close();
}
in.close();
return 0;
}

-------------------------------------------------------------
The output is

file0.dat ok
file1.dat file can't open
file2.dat file can't open
file3.dat file can't open
file4.dat file can't open
file5.dat file can't open
file6.dat file can't open
file7.dat file can't open
file8.dat file can't open
file9.dat file can't open

I have closed the file inside the for loop so that each file can be opened by the same ifstream in_file. According to my guess, this should cause problem. However, I can't see any other problem.
Anybody has idea?
Thanks.

NMTop40
September 28th, 2005, 12:02 PM
I don't think you can recycle an ifstream. Define it inside the for loop though and it will work. Thus:


#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{

string name;
ifstream in( "file_list" );


for(int i=0; i<10; i++)
{
getline(in,name);
ifstream in_file( name.c_str() );

if(in_file.fail())
cout << name << " file can't open" << endl;
else
cout << name << " ok" << endl;
}
in.close();
return 0;
}

No need to explicitly close it either.

manojg
September 28th, 2005, 12:23 PM
Thank you very much NMTop40.

SuperKoko
September 28th, 2005, 01:02 PM
The NMTop40 approach of the problem is the best way.
However, you can also try to call in_file.clear() after haved closed the file, because closing the file may set the eofbit state flag.