使用标准C++/C++11,14,17/C检查文件是否存在的最快方法?

我想找到最快的方法来检查一个文件是否存在于标准C++11、14、17或C中。我有数千个文件,在对它们执行操作之前,我需要检查它们是否都存在。在下面的函数中,我可以编写什么来代替/*SOMETHING*/

内联bool exist(const std::string&name)
{
/*某物*/
}

我编写了一个测试程序,每种方法都运行了100000次,一半运行在存在的文件上,另一半运行在不存在的文件上

#包括<sys/stat.h>
#包括<unistd.h>
#包括<字符串>
#包括<fstream>
内联bool exists\u test0(const std::string和name){
ifstream f(name.c_str());
返回f.good();
}
内联bool exists_test1(const std::string和name){
如果(FILE*FILE=fopen(name.c_str(),“r”){
fclose(文件);
返回true;
}否则{
返回false;
}   
}
内联bool exists_test2(const std::string和name){
return(access(name.c_str(),F_OK)!=-1);
}
内联bool exists_test3(const std::string和name){
结构统计缓冲区;
返回(stat(name.c_str(),&buffer)==0);
}

在5次运行中平均运行100000次呼叫的总时间结果

方法
时间
存在\u test0(ifstream) 0.485s
存在\u test1(文件fopen) 0.302s
存在\u test2(posix access()) 0.202s
存在\u test3(posix stat()) 0.134s

stat()函数在我的系统(Linux,用g++编译)上提供了最好的性能,如果您出于某种原因拒绝使用POSIX函数,则最好使用标准的fopen调用

发表评论