regarding file existence check within a for loop in C++
I 开发者_如何学Goam attempting to check if a file exists, and then if so proceed with a task and if not to just output that there is no such file. I have done this in other code but it doesn't seem to be working with my current code.
The basics of it read:
count=argc;
for(i=0; i < count-1; i++)
{
filename[i] = argv[i+1];
}
for( i=0; i < count-1; i++)
{
int tempi=i;
ifstream infile(filename[i].c_str());
if(infile)
{
//do things
}
else
{
cout<<"no file"<<endl;
}
You need to call infile.is_open()
. Also, do you plan to do something with the file if it exists, or not?
The canonical way to access argv is:
int main( int argc, char * argv[] ) {
for ( int i = 1; i < argc; i++ ) {
// do something with argv[i]
}
}
infile
, in the conditional, evaluates to false
when the stream is in a "bad" state.
However, merely failing to open a file does not leave the stream in a bad state (welcome to C++!). Only after attempting to read from the stream would this mechanism work for you.
Fortunately, you can use infile.is_open()
to explicitly test for whether the stream was opened or not.
Edit
The above is not true.
Testing the stream state is sufficient, and I can't see anything wrong with your code.
精彩评论