好问题
Good  Question
  • 首 页
  • 问题
    • PHP
    • JAVA
    • CPlusPlus
    • C#
    • SQL
  • 关 于
  • 联 系
用来检查一个文件是否存的标准C++或者C++11或者C的最快的方式? 关闭 返回上一级  

用来检查一个文件是否存的标准C++或者C++11或者C的最快的方式?
+ 查看更多

发布日期:2018-02-26 10:15
分类:CPlusPlus
浏览次数:103
如下:我想要找一个最快的方式用来检查一个文件是否存在于标准C++或者C++11或者C中.我有几千个文件并且在操作他们之前,我需要检查他们是否都存在。在下面的函数中,我应该在/* SOMETHING */的位置写什么?
inline bool exist(const std::string& name)
{
    /* SOMETHING */
}

回答:

好的,我罗列了一个会运行这些方法100000的测试程序,其中一半的文件存在,一半的文件不存在。
#include 
#include 
#include 

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); 
}
运行100000次总时间的结果都需要5次运行结果取平均.
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**
在我的系统中stat()函数提供最佳的性能(Linux,用g++编译),如果你因为某些原因拒绝使用POSIX函数,调用标准fopen函数是最好的办法.
上一篇C++中检查文件是否存在的最好方式(跨平台)是什么?
使用C或者C++时,我怎样才能在目录中获得文件列表?下一篇
下一篇使用C或者C++时,我怎样才能在目录中获得文件列表?

最新文章

  • 函数`__construct`用来干嘛的
    发布日期:2018-03-26
  • 通过访客的IP得到他们的地区
    发布日期:2018-03-26
  • 合并两个PHP对象的最好的方法是什么?
    发布日期:2018-03-26
  • 该如何把一该如何把一个对象转化成数组?
    发布日期:2018-03-26
  • 什么是输出缓冲区?
    发布日期:2018-03-26
  • 在PHP中怎么把用逗号分隔的字符串分隔在一个数组里?
    发布日期:2018-03-26
  • 在PHP中使用foreach循环时查找数组的最后一个元素
    发布日期:2018-03-26
关于好问
收集整理一些有用的问题和回答,造福中国的程序旺和IT喵们!
友情链接
起飞页 
相关信息
版权声明
Copyright © 2016 - 2022  苏州卡达网络科技有限公司 备案号:苏ICP备09008221号