使用ifstream检查文件是否成功打开

ant*_*009 18 c++ io ifstream

我有以下将打开文件进行阅读.但是,我想检查以确保文件已成功打开,因此我使用失败来查看是否已设置标志.但是,我不断收到以下错误:

我是C++的新手,因为我来自C.所以我不确定我是否理解这个错误:

不能调用成员函数'bool std :: basic_ios <_CharT,_Traits> :: fail()const [with _CharT = char,_Traits = std :: char_traits]'没有对象

码:

int devices::open_file(std::string _file_name)
{
    ifstream input_stream;

    input_stream.open(_file_name.c_str(), ios::in);

    if(ios::fail() == true) {
        return -1;
    }

    file_name = _file_name;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sve*_*ven 19

你可以这样做:

int devices::open_file(std::string _file_name)
{
    ifstream input_stream;    
    input_stream.open(_file_name.c_str(), ios::in);
    if(!input_stream)
    {
        return -1;
    } 
    file_name = _file_name;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

失败()不是一个静态方法,你必须调用它的实例不是一个类型的,所以如果你想使用失败(),替换!input_streaminput_stream.fail()在我上面的代码.

我不得不想知道你在这里想要达到的目标.您正在打开该文件并立即再次关闭它.你只是想检查文件是否存在?

  • 请问为什么在`ifstream`中使用`ios :: in`标志? (3认同)

Duy*_*ặng 7

你也可以使用std::ifstream::is_open. 如果文件已打开并与此流对象关联,则返回 true。

// ifstream::is_open
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {
  std::ifstream ifs ("test.txt");

  if (ifs.is_open()) {
    // print file:
    char c = ifs.get();
    while (ifs.good()) {
      std::cout << c;
      c = ifs.get();
    }
  }
  else {
    // show message:
    std::cout << "Error opening file";
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

http://www.cplusplus.com/reference/fstream/ifstream/is_open/


use*_*116 5

您的错误是因为您将其用作ios::fail()静态方法,而实际上它是成员方法。

if (input_stream.fail())
{
    ...
}
Run Code Online (Sandbox Code Playgroud)