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

  2. #include

  3. #include

  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

  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 

你可能感兴趣的:(c++学习)