Checking if a file opened successfully with ifstream

后端 未结 4 1248
我在风中等你
我在风中等你 2020-12-10 01:28

I have the following that will open a file for reading. However, I want to check to make sure that the file was open successfully, so I am using the fail to see if the flags

相关标签:
4条回答
  • 2020-12-10 02:01

    you can also use std::ifstream::is_open. Returns true if a file is open and associated with this stream object.

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

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

    0 讨论(0)
  • 2020-12-10 02:05

    You can simply do this:

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

    fail() is not a static method, you must call it on an instance not a type, so if you want to use fail(), replace !input_stream with input_stream.fail() in my code above.

    I do have to wonder what you're trying to achieve here. You're opening the file and immediately close it again. Are you simply trying to check if the file exists?

    0 讨论(0)
  • 2020-12-10 02:15

    Your error is because you are using ios::fail() as a static method when it is actually a member method.

    if (input_stream.fail())
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-10 02:22

    You have to call fail() on the stream object. A more idiomatic way of doing this is:

    input_stream.open(_file_name.c_str(), ios::in);
    
    if( ! input_stream ) {
        return -1;
    }
    
    0 讨论(0)
提交回复
热议问题