bug^君 2012-10-08 01:10 采纳率: 25%
浏览 1148
已采纳

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

I would like to find the fastest way to check if a file exist in standard C++11, C++, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of /* SOMETHING */ in the following function?

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

转载于:https://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c

  • 写回答

17条回答 默认 最新

  • larry*wei 2012-10-08 01:43
    关注

    Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn't.

    #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); 
    }
    

    Results for total time to run the 100,000 calls averaged over 5 runs,

    Method exists_test0 (ifstream): **0.485s**
    Method exists_test1 (FILE fopen): **0.302s**
    Method exists_test2 (posix access()): **0.202s**
    Method exists_test3 (posix stat()): **0.134s**
    

    The stat() function provided the best performance on my system (Linux, compiled with g++), with a standard fopen call being your best bet if you for some reason refuse to use POSIX functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(16条)

报告相同问题?

悬赏问题

  • ¥15 博通raid 的写入速度很高也很低
  • ¥15 目标计数模型训练过程中的问题
  • ¥100 Acess连接SQL 数据库后 不能用中文筛选
  • ¥15 用友U9Cloud的webapi
  • ¥20 电脑拓展屏桌面被莫名遮挡
  • ¥20 ensp,用局域网解决
  • ¥15 Python语言实验
  • ¥15 我每周要在投影仪优酷上自动连续播放112场电影,我每一周遥控操作一次投影仪,并使得电影永远不重复播放,请问怎样操作好呢?有那么多电影看吗?
  • ¥20 电脑重启停留在grub界面,引导出错需修复
  • ¥15 matlab透明图叠加