来源:https://blog.csdn.net/xfxf996/article/details/106235087/
分别使用 std::ifstream
、fopen
、access
和stat
测试文件是否存在。
#include <sys/stat.h> // stat()
#include <unistd.h> // access()
#include <iostream>
#include <fstream>
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " filepath" << std::endl;
return 1;
}
const std::string filepath = argv[1];
// use ifstream testing
std::ifstream f(filepath.c_str());
auto func = "ifstream";
if(f.good()) {
std::cout << func << ": file exists: " << filepath << std::endl;
} else {
std::cout << func << ": file not exists: " << filepath << std::endl;
}
// use fopen
func = "fopen";
FILE *fp = fopen(filepath.c_str(), "r");
if(fp) {
std::cout << func << ": file exists: " << filepath << std::endl;
fclose(fp);
} else {
std::cout << func << ": file not exists: " << filepath << std::endl;
}
// use access
func = "access";
if(access(filepath.c_str(), F_OK) != -1) {
std::cout << func << ": file exists: " << filepath << std::endl;
} else {
std::cout << func << ": file not exists: " << filepath << std::endl;
}
// use stat
func = "stat";
struct stat buffer;
if(stat (filepath.c_str(), &buffer) == 0) {
std::cout << func << ": file exists: " << filepath << std::endl;
} else {
std::cout << func << ": file not exists: " << filepath << std::endl;
}
return 0;
}