|
-
September 28th, 2005, 11:54 AM
#1
loop over open file
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.
-
September 28th, 2005, 12:02 PM
#2
Re: loop over open file
I don't think you can recycle an ifstream. Define it inside the for loop though and it will work. Thus:
Code:
#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.
-
September 28th, 2005, 12:23 PM
#3
Re: loop over open file
Thank you very much NMTop40.
-
September 28th, 2005, 01:02 PM
#4
Re: loop over open file
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.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|