Posted By

StraightforAward on 10/11/11


Tagged

file path check access exist


Versions (?)

Check if a file exists


 / Published in: C++
 

URL: http://www.developer.nokia.com/Community/Wiki/CS001101_-_Checking_if_a_file_exists_in_C_and_C%2B%2B

  1. #include <stdio.h> //FILE, fopen(), fclose()
  2. #include <sys/stat.h> //stat, stat()
  3. #include <string> //string
  4. #include <fstream> //fstream
  5. #include <iostream> //cout
  6.  
  7. using namespace std;
  8.  
  9. bool OpenCFileExists(const char* filename)
  10. {
  11. FILE* fp = NULL;
  12.  
  13. //this will fail if more capabilities to read the
  14. //contents of the file is required (e.g. \private\...)
  15. fp = fopen(filename, "r");
  16.  
  17. if(fp != NULL)
  18. {
  19. fclose(fp);
  20. return true;
  21. }
  22. fclose(fp);
  23.  
  24. return false;
  25. }
  26.  
  27. bool OpenCppFileExists(const string& filename)
  28. {
  29. fstream fin;
  30.  
  31. //this will fail if more capabilities to read the
  32. //contents of the file is required (e.g. \private\...)
  33. fin.open(filename.c_str(), ios::in);
  34.  
  35. if(fin.is_open())
  36. {
  37. fin.close();
  38. return true;
  39. }
  40. fin.close();
  41.  
  42. return false;
  43. }
  44.  
  45. bool FileExists(const char* filename)
  46. {
  47. struct stat info;
  48. int ret = -1;
  49.  
  50. //get the file attributes
  51. ret = stat(filename, &info);
  52. if(ret == 0)
  53. {
  54. //stat() is able to get the file attributes,
  55. //so the file obviously exists
  56. return true;
  57. }
  58. else
  59. {
  60. //stat() is not able to get the file attributes,
  61. //so the file obviously does not exist or
  62. //more capabilities is required
  63. return false;
  64. }
  65. }
  66. bool FileExists(const string& filename)
  67. {
  68. return FileExists(filename.c_str());
  69. }
  70.  
  71. //the simple test program for above functions
  72. int main()
  73. {
  74. string filename;
  75.  
  76. cout << "Enter the filename (empty line quit):" << endl;
  77. cout << ">";
  78.  
  79. while(getline(cin, filename))
  80. {
  81. string result;
  82.  
  83. if(filename.size() == 0)
  84. break;
  85.  
  86. OpenCFileExists(filename.c_str()) ?
  87. result = " found!" : result = " not found!";
  88. cout << "OpenCFileExists: " << filename << result << endl;
  89.  
  90. OpenCppFileExists(filename) ? result = " found!" : result = " not found!";
  91. cout << "OpenCppFileExists: " << filename << result << endl;
  92.  
  93. FileExists(filename) ? result = " found!" : result = " not found!";
  94. cout << "FileExists: " << filename << result << endl;
  95.  
  96. cout << ">";
  97. }
  98.  
  99.  
  100. return 0;
  101.  
  102. }

Report this snippet  

You need to login to post a comment.