检测文件是否打开

Detecting if a file is open

如何检测文件是否在 C++ 中打开? 我正在尝试使用这样的代码:

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

您正在寻找函数 is_open()

if(file.is_open()){}
if(file.is_open())

您正在调用 ifstream::is_open() 函数