【问题标题】:Detecting if a file is open检测文件是否打开
【发布时间】: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 &gt;&gt; some_variable) { /* do something */ }

标签: c++ file detection file-exists


【解决方案1】:

你正在寻找函数 is_open()

if(file.is_open()){}

【讨论】:

    【解决方案2】:
    if(file.is_open())
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 1970-01-01
      相关资源
      最近更新 更多