【发布时间】:2015-08-30 04:18:27
【问题描述】:
如何检测文件是否在 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";
}
【问题讨论】:
-
你试过
file.is_open()吗? -
你的意思是'if (file.is_open) ...'吗?
-
不,我的意思是
file.is_open(),std::istream::is_open() -
可以通过
is_open成员函数完成对文件是否打开的所需检查。 -
在某些情况下,您不需要明确检查文件是否打开,只需执行例如
while (file >> some_variable) { /* do something */ }
标签: c++ file detection file-exists