How to check if a file exists in C++?
In C++, you can use the std::ifstream class to check if a file exists. The std::ifstream class is an input stream class used for reading files in the C++ standard library.
Here is an example code using std::ifstream to check if a file exists.
#include <iostream>
#include <fstream>
#include <string>
bool fileExists(const std::string& filename) {
std::ifstream file(filename);
return file.good(); // 如果文件存在,则返回true,否则返回false
}
int main() {
std::string filename = "example.txt";
if (fileExists(filename)) {
std::cout << "文件存在" << std::endl;
} else {
std::cout << "文件不存在" << std::endl;
}
return 0;
}
In the above code, the fileExists function utilizes the std::ifstream class to open the specified file. If the file exists, the file.good() function will return true, otherwise it will return false. Based on this return value, we can determine if the file exists.