C++17及以上版本,检查文件是否存在可以使用filesystem库
如果使用的是C++11或C++14,标准库并没有直接提供这样的功能。
可以使用平台特定的API,例如在Windows上使用 _access
函数,或在POSIX兼容系统(如Linux和macOS)上使用 access
函数。
示例:
#include <iostream>
#include <unistd.h> // 包含access函数
int main() {
const char* filePath = "example.txt"; // 替换为你想要检查的文件路径
if (access(filePath, F_OK) != -1) {
//F_OK 标志用于检查文件是否存在。如果文件存在,access 返回0;否则返回-1。
std::cout << "文件存在" << std::endl;
} else {
std::cout << "文件不存在" << std::endl;
}
return 0;
}