Checking if a file opened successfully with ifstream

后端 未结 4 1254
我在风中等你
我在风中等你 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      // std::cout
    #include       // 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/

提交回复
热议问题