Search code examples
c++filedetectionfile-exists

Detecting if a file is open


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";
    }

Solution

  • You are looking for the function is_open()

    if(file.is_open()){}