c++判断文件是否存在

 

Fastest way to check if a file exist using standard C++/C++11/C?

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

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.

 
  1. #include <sys/stat.h>

  2. #include <unistd.h>

  3. #include <string>

  4.  
  5. inline bool exists_test0 (const std::string& name) {

  6. ifstream f(name.c_str());

  7. return f.good();

  8. }

  9.  
  10. inline bool exists_test1 (const std::string& name) {

  11. if (FILE *file = fopen(name.c_str(), "r")) {

  12. fclose(file);

  13. return true;

  14. } else {

  15. return false;

  16. }

  17. }

  18.  
  19. inline bool exists_test2 (const std::string& name) {

  20. return ( access( name.c_str(), F_OK ) != -1 );

  21. }

  22.  
  23. inline bool exists_test3 (const std::string& name) {

  24. struct stat buffer;

  25. return (stat (name.c_str(), &buffer) == 0);

  26. }

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

 
  1. Method exists_test0 (ifstream): **0.485s**

  2. Method exists_test1 (FILE fopen): **0.302s**

  3. Method exists_test2 (posix access()): **0.202s**

  4. 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.

Also in Visual Studio 2015: 

 
  1. #include <experimental/filesystem>

  2.  
  3. bool file_exists(std::string fn)

  4. {

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

  6. }

since C++17, only:

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

转载于:https://blog.csdn.net/sinat_16577223/article/details/82025089 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值