FileMapper.hpp 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #pragma once
  2. #include <windows.h>
  3. #include <string>
  4. #include "ExceptionSystem.hpp"
  5. #include "ResourceGuardWin32.hpp"
  6. #undef __BASE_FILE__
  7. #define __BASE_FILE__ "FileMapper.hpp"
  8. #if defined(UNICODE) || defined(_UNICODE)
  9. using String = std::wstring;
  10. #else
  11. using String = std::string;
  12. #endif
  13. class FileMapper {
  14. private:
  15. ResourceGuard<FileHandleTraits> _FileHandle;
  16. ResourceGuard<GenericHandleTraits> _FileMapHandle;
  17. ResourceGuard<MapViewTraits> _FileView;
  18. public:
  19. static bool IsExist(const String&& FilePath) {
  20. DWORD dwAttr = GetFileAttributes(FilePath.c_str());
  21. if (dwAttr == INVALID_FILE_ATTRIBUTES) {
  22. if (GetLastError() == ERROR_FILE_NOT_FOUND)
  23. return false;
  24. else
  25. throw SystemError(__BASE_FILE__, __LINE__, GetLastError(),
  26. "GetFileAttributes fails.");
  27. } else {
  28. return (dwAttr & FILE_ATTRIBUTE_DIRECTORY) == 0;
  29. }
  30. }
  31. template<typename _Type>
  32. _Type* GetView() const noexcept {
  33. return reinterpret_cast<_Type*>(_FileView.GetHandle());
  34. }
  35. void MapFile(const String& FileName) {
  36. ResourceGuard<FileHandleTraits> TempFileHandle;
  37. ResourceGuard<GenericHandleTraits> TempFileMapHandle;
  38. ResourceGuard<MapViewTraits> TempFileView;
  39. TempFileHandle.TakeHoldOf(
  40. CreateFile(FileName.c_str(),
  41. GENERIC_READ | GENERIC_WRITE,
  42. FILE_SHARE_READ,
  43. NULL,
  44. OPEN_EXISTING,
  45. FILE_ATTRIBUTE_NORMAL,
  46. NULL)
  47. );
  48. if (TempFileHandle.IsValid() == false)
  49. throw SystemError(__BASE_FILE__, __LINE__, GetLastError(),
  50. "CreateFile fails.");
  51. TempFileMapHandle.TakeHoldOf(
  52. CreateFileMapping(TempFileHandle,
  53. NULL,
  54. PAGE_READWRITE,
  55. 0,
  56. 0,
  57. NULL)
  58. );
  59. if (TempFileMapHandle.IsValid() == false)
  60. throw SystemError(__BASE_FILE__, __LINE__, GetLastError(),
  61. "CreateFileMapping fails.");
  62. TempFileView.TakeHoldOf(
  63. MapViewOfFile(TempFileMapHandle,
  64. FILE_MAP_READ | FILE_MAP_WRITE,
  65. 0,
  66. 0,
  67. 0)
  68. );
  69. if (TempFileView.IsValid() == false)
  70. throw SystemError(__BASE_FILE__, __LINE__, GetLastError(),
  71. "MapViewOfFile fails.");
  72. _FileView.Release();
  73. _FileView = std::move(TempFileView);
  74. _FileMapHandle.Release();
  75. _FileMapHandle = std::move(TempFileMapHandle);
  76. _FileHandle.Release();
  77. _FileHandle = std::move(TempFileHandle);
  78. }
  79. void Release() {
  80. _FileView.Release();
  81. _FileMapHandle.Release();
  82. _FileHandle.Release();
  83. }
  84. };