Click here to Skip to main content
15,917,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in this code when i comment these two lines the output "Error opening file" does not display to the screen but when i do not comment these two below commented lines the output "Error opening file" is displayed by the program , why it is?

C++
int main()
{
    fstream f;
    //f.open("D:\\Test",ios::in);
    //f.close();
    
    if(!f)
          cout<<"Error opening file";
          
    getch();
    return 0;
}
Posted
Updated 16-Mar-12 8:20am
v2
Comments
enhzflep 16-Mar-12 14:11pm    
Well, do you have a file named "Test", in the root directory of D drive?
Ashutosh_g 16-Mar-12 14:23pm    
yes
Ashutosh_g 16-Mar-12 14:27pm    
yes the file test is in directory D

I recommend you to have a look here[^]

You are opening and closing the file. By closing you disassociate the file of the fstream.

quote from the site:
Once closed, the same file stream object may be used to open another file
[/quote]

On the other hand... open file does not necessary mean create file.
 
Share this answer
 
Looks like the open operation fails. Hence, the failbit flag gets set in the fstream object and that is what's tested in the !f expression.

When you comment the two lines out you have a brand new fstream object which has the failbit not set -- no error has occurred yet.

So my guess would be that you don't have a file named "D:\\Test". Perhaps you have a file "Test.<something>" with another file type in the root directory of drive D:?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900