我想找到最快的方法来检查标准 C++11、14、17 或 C 中是否存在文件。我有数千个文件,在对它们进行操作之前,我需要检查它们是否全部存在。我可以写什么来代替/* SOMETHING */
在下面的函数中?
inline bool exist(const std::string& name)
{
/* SOMETHING */
}
好吧,我编写了一个测试程序,将这些方法中的每一个运行 100,000 次,一半运行在存在的文件上,一半运行在不存在的文件上。
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test0 (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
inline bool exists_test1 (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
inline bool exists_test2 (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
inline bool exists_test3 (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
运行 100,000 个调用的总时间的结果在 5 次运行中平均,
Method |
Time |
exists_test0 (ifstream) |
0.485s |
exists_test1 (FILE fopen) |
0.302s |
exists_test2 (posix access()) |
0.202s |
exists_test3 (posix stat()) |
0.134s |
The stat()
函数在我的系统(Linux,编译时使用g++
),有一个标准fopen
如果您出于某种原因拒绝使用 POSIX 函数,那么 call 是您最好的选择。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)