在C++中,可以使用 <fstream> 头文件中的 ifstream 类来判断路径是否存在。下面是一个示例代码:
#include <iostream> #include <fstream> bool pathExists(const std::string& path) { std::ifstream file(path); return file.good(); } int main() { std::string path = "C:/path/to/file.txt"; if (pathExists(path)) { std::cout << "Path exists!" << std::endl; } else { std::cout << "Path does not exist!" << std::endl; } return 0; } 在上面的代码中,pathExists 函数接受一个路径字符串作为参数,使用 ifstream 类尝试打开该路径对应的文件。如果打开成功,则说明路径存在,返回 true;否则,返回 false。在 main 函数中,我们可以根据返回值来确定路径是否存在,并进行相应的操作。