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

新手上路,请多包涵

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

 inline bool exist(const std::string& name)
{
    /* SOMETHING */
}

原文由 Vincent 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 730
2 个回答

好吧,我拼凑了一个测试程序,将这些方法中的每一个运行了 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 次运行,

方法时间exists_test0 (ifstream)0.485sexists_test1 (文件打开)0.302sexists_test2 (posix访问())0.202sexists_test3 (posix stat())0.134s

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

原文由 PherricOxide 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题