在C++中(c++17 以上),你可以使用 <filesystem>
头文件中的std::filesystem::exists()
函数来检查文件是否存在。
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
std::string filePath = "/path/to/file.txt";
if (fs::exists(filePath)) {
std::cout << "File exists." << std::endl;
} else {
std::cout << "File does not exist." << std::endl;
}
std::string folderPath = "/path/to/folder";
if (fs::exists(folderPath) && fs::is_directory(folderPath)) {
std::cout << "Folder exists." << std::endl;
} else {
std::cout << "Folder does not exist." << std::endl;
}
return 0;
}