Detecting if a file is open

277 views Asked by At

How can I detect if a file is open in C++? I am trying to use a code like this:

    int main()
    {
        ifstream file("file.txt");
        if ( /*here comes the check if file is open*/ ) cout<<"File open successfully"; else cout<<"File couldn't be opened. Check if the file is not used by another program or if it exists";
    }
2

There are 2 answers

0
Alex On BEST ANSWER

You are looking for the function is_open()

if(file.is_open()){}
0
Steephen On
if(file.is_open())

You are calling ifstream::is_open() function