Search code examples
c++implicit-conversion

Why can I put an ifstream file in an if condition?


I am trying to check if the file opened successfully. And I found this method to open files to be read:

char path[]="data/configuration.txt";
std::ifstream configFile(path, std::ifstream::in);
if(configFile) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

The question is what exactly does if checks for ?

Because I also found the following method of checking if a file is open:

char path[]="data/configuration.txt";
std::ifstream configFile;
configFile.open(path, std::ifstream::in);
if(configFile.is_open()) {
  std::cout<<"Successfully opened file: "<<path<<std::endl;
} else {
  std::cout<<"Error, Could not open file: "<<path<<std::endl;
}

I do have some other questions. For example, what is the difference between the two methods of opening the file ? Also, what would be the difference in the two if conditions ?

I think these are similar methods that end up with the same result, because I can use std::ifstream methods, like is_open with both opening methods:

std::ifstream configFile(path, std::ifstream::in);
configFile.open(path, std::ifstream::in);

Solution

  • std::ifstream could contextually convert to bool via std::basic_ios<CharT,Traits>::operator bool, which is inherited from std::basic_ios.

    Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

    Note that it performs different check with std::basic_ifstream<CharT,Traits>::is_open.

    Checks if the file stream has an associated file. Effectively calls rdbuf()->is_open().