我正在尝试检查文件是否成功打开。我发现这种方法可以打开要读取的文件:
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;
}
问题是 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;
}
我还有其他问题。例如,这两种打开文件的方法有什么区别?另外,这两个 if
条件有什么区别?
我认为这些是最终得到相同结果的相似方法,因为我可以使用 std::ifstream
方法,如 is_open
两种打开方法:
std::ifstream configFile(path, std::ifstream::in);
configFile.open(path, std::ifstream::in);
最佳答案
std::ifstream
可以 contextually convert to bool
通过 std::basic_ios<CharT,Traits>::operator bool
,它继承自 std::basic_ios
.
Returns
true
if the stream has no errors and is ready for I/O operations. Specifically, returns!fail()
.
请注意,它对 std::basic_ifstream<CharT,Traits>::is_open
执行不同的检查.
Checks if the file stream has an associated file. Effectively calls
rdbuf()->is_open()
.
关于c++ - 为什么我可以将 ifstream 文件置于 if 条件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818535/