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

标签 c++ c file stream

我想找到最快的方法来检查标准 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); 
}

在 5 次运行中平均运行 100,000 次调用的总时间结果,

<头>
方法 时间
exists_test0 (ifstream) 0.485s
exists_test1 (FILE fopen) 0.302s
exists_test2 (posix access()) 0.202s
exists_test3 (posix stat()) 0.134s

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

关于c++ - 使用标准 C++/C++11、14、17/C 检查文件是否存在的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12774207/

相关文章:

c++ - 使用类成员函数作为回调?

c++ - 如何使用c中的mount函数?

c - 读取未知大小的字符串

计算字符数组中的个数

c - 参数传递问题

Android检查文件是否存在()不起作用

c++ - 结构数组有什么问题?

c++ - 在关联容器中使用 emplace(args&& ...)

java - 读取文件错误

java - spring boot 文件上传不起作用