我想找到最快的方法来检查标准 C++11、14、17 或 C 中是否存在文件。我有数千个文件,在对它们进行操作之前,我需要检查它们是否都存在。在以下函数中,我可以写什么来代替 /* SOMETHING */
?
inline bool exist(const std::string& name)
{
/* SOMETHING */
}
原文由 Vincent 发布,翻译遵循 CC BY-SA 4.0 许可协议
好吧,还有更简单的方法
#include <fstream>
#include <iostream>
void FileExists(std::string myfile){
std::ifstream file(myfile.c_str());
if (file) {
std::cout << "file exists" << std::endl;
}
else {
std::cout << "file doesn't exist" << std::endl;
}
}
int main() {
FileExists("myfile.txt");
return 0;
}
原文由 jack chyna 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
好吧,我拼凑了一个测试程序,将这些方法中的每一个运行了 100,000 次,一半在存在的文件上,一半在不存在的文件上。
运行 100,000 次调用的总时间结果平均超过 5 次运行,
方法时间
exists_test0
(ifstream)0.485sexists_test1
(文件打开)0.302sexists_test2
(posix访问())0.202sexists_test3
(posix stat())0.134sstat()
函数在我的系统上提供了最好的性能(Linux,用g++
编译),标准fopen
如果你出于某种原因调用是你最好的选择拒绝使用 POSIX 函数。