使用标准C++/C++11、14、17/C检查文件是否存在的最快方法? [英] Fastest way to check if a file exists using standard C++/C++11,14,17/C?

查看:71
本文介绍了使用标准C++/C++11、14、17/C检查文件是否存在的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望找到最快的方法来检查文件是否存在于标准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次,

<标题> <正文>
方法 时间
exists_test0(Ifstream) 0.485s
exists_test1(文件fopen) 0.302s
exists_test2(POSIX access()) 0.202s
exists_test3(POSIX stat()) 0.134s

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

这篇关于使用标准C++/C++11、14、17/C检查文件是否存在的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆