为什么可以将ifstream文件置于if条件中?

ble*_*ah1 3 c++ implicit-conversion

我正在尝试检查文件是否成功打开。我发现这种方法可以打开要读取的文件:

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;
}
Run Code Online (Sandbox Code Playgroud)

问题是究竟要if检查什么?

因为我还发现了以下检查文件是否打开的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

我还有其他问题。例如,两种打开文件的方法有什么区别?另外,这两个if条件有什么区别?

我认为这些是相似的方法,最终会得到相同的结果,因为我可以使用两种打开方法std::ifstream一样的is_open方法:

std::ifstream configFile(path, std::ifstream::in);
configFile.open(path, std::ifstream::in);
Run Code Online (Sandbox Code Playgroud)

son*_*yao 8

std::ifstream可以上下文转换为boolstd::basic_ios<CharT,Traits>::operator bool继承的via std::basic_ios

返回true如果流没有错误并准备进行I / O操作。具体来说,return !fail()

请注意,它会使用进行不同的检查std::basic_ifstream<CharT,Traits>::is_open

检查文件流是否具有关联文件。有效通话rdbuf()->is_open()