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

关于C-14呼气检查的问题,在c++ check file exist中经常遇到, 我想找到最快的方法来检查文件是否存在于标准 C ++ 11,14,17 或 C 中。我有数千个文件,在对它们做一些事情之前,我需要检查它们是否存在。

我想找到最快的方法来检查文件是否存在于标准 C ++ 11,14,17 或 C 中。我有数千个文件,在对它们做一些事情之前,我需要检查它们是否存在。

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

好吧,我把一个测试程序放在一起,运行这些方法中的每一个 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); 
}

运行 10 万个调用的总时间平均超过 5 次运行的结果,

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

246

备注:在 C ++ 14 中,一旦filesystem TS将完成并采用,解决方案将是使用:

std::experimental::filesystem::exists("helloworld.txt");

自 C ++ 17 以来,只有:

std::filesystem::exists("helloworld.txt");
131

我使用这段代码,到目前为止它与我一起工作。这不使用 C ++ 的许多花哨的功能:

bool is_file_exist(const char *fileName)
{
    std::ifstream infile(fileName);
    return infile.good();
}
41

对于那些喜欢提升的人:

 boost::filesystem::exists(fileName)

或者,由于 ISO C ++ 17:

 std::filesystem::exists(fileName)

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(603)
Cd拷贝到电脑:在没有iTunes的情况下将音乐和有声读物的文件夹复制到iPhone(并且不必首先标记我的所有媒体)
上一篇
Pa 46:Lista paíse có digo
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(25条)