path_exists.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // $Id$
  3. //
  4. #include<__vic/fs.h>
  5. #include<__vic/error.h>
  6. #include<__vic/string_buffer.h>
  7. #include<__vic/windows/wchar.h>
  8. #include<__vic/windows/find_file.h>
  9. #include<__vic/windows/throw_last_error.h>
  10. #include<windows.h>
  11. namespace __vic {
  12. namespace {
  13. //----------------------------------------------------------------------------
  14. bool get_file_attr(const char *path, DWORD &attr, const char *what)
  15. {
  16. // TODO: the call doesn't follow symbolic links as opposed to POSIX stat()
  17. // FILE_ATTRIBUTE_REPARSE_POINT is set for symlink
  18. windows::FindFile ff;
  19. if(ff.FindFirst(windows::utf8to16(path)))
  20. {
  21. attr = ff.dwFileAttributes;
  22. if(ff.FindNext()) throw exception(__vic::msg(256) <<
  23. "More than one entry of \"" << path << "\" has been found");
  24. return true;
  25. }
  26. DWORD err = ::GetLastError();
  27. switch(err)
  28. {
  29. case ERROR_FILE_NOT_FOUND:
  30. return false;
  31. }
  32. windows::throw_last_error(__vic::msg(256) <<
  33. "Can't get attributes of " << what << " \"" << path << '"', err);
  34. }
  35. //----------------------------------------------------------------------------
  36. } // namespace
  37. //----------------------------------------------------------------------------
  38. bool path_exists(const char *path)
  39. {
  40. #if 0
  41. if(::PathFileExistsW(windows::utf8to16(path))) // depends on Shlwapi.dll
  42. return true;
  43. DWORD err = ::GetLastError();
  44. // TODO
  45. #else
  46. DWORD attr;
  47. return get_file_attr(path,attr,"path");
  48. #endif
  49. }
  50. //----------------------------------------------------------------------------
  51. bool file_exists(const char *path)
  52. {
  53. DWORD attr;
  54. // TODO: no special attribute to distinguish regular file
  55. // so using elimination approach
  56. return get_file_attr(path,attr,"file") &&
  57. !(attr & FILE_ATTRIBUTE_DIRECTORY);
  58. }
  59. //----------------------------------------------------------------------------
  60. bool dir_exists(const char *path)
  61. {
  62. DWORD attr;
  63. return get_file_attr(path,attr,"dir") && (attr & FILE_ATTRIBUTE_DIRECTORY);
  64. }
  65. //----------------------------------------------------------------------------
  66. } // namespace