Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

  1. #include "stdafx.h"
  2. #include "filemap.h"
  3. CFileMap::CFileMap()
  4. {
  5. m_Memory = NULL;
  6. m_FileMapping = NULL;
  7. m_FileHandle = NULL;
  8. m_FileSize = 0;
  9. }
  10. CFileMap::~CFileMap()
  11. {
  12. bClose();
  13. }
  14. BOOL CFileMap::bOpen(LPCTSTR FileName,BOOL ReadOnly)
  15. {
  16. BOOL bRet = FALSE;
  17. m_FileHandle = CreateFile(
  18. FileName,
  19. GENERIC_READ,
  20. (ReadOnly) ? FILE_SHARE_READ : FILE_SHARE_READ | FILE_SHARE_WRITE,
  21. NULL,
  22. OPEN_EXISTING,
  23. 0,
  24. NULL);
  25. if(m_FileHandle == INVALID_HANDLE_VALUE) {
  26. fprintf(stderr,"Open file error ! %X\n", GetLastError());
  27. goto Error;
  28. }
  29. m_FileSize = ::GetFileSize(m_FileHandle,NULL);
  30. if(m_FileSize == -1) {
  31. fprintf(stderr,"Get file size error ! %X\n", GetLastError());
  32. goto Error;
  33. }
  34. if(!m_FileSize) {
  35. fprintf(stderr,"File size is 0 !\n");
  36. goto Error;
  37. }
  38. m_FileMapping= CreateFileMapping(
  39. m_FileHandle,
  40. NULL,
  41. (ReadOnly) ? PAGE_READONLY : PAGE_READWRITE,
  42. 0,
  43. 0 ,
  44. NULL);
  45. if(m_FileMapping == NULL) {
  46. fprintf(stderr,"Unable to map file ! %X\n", GetLastError());
  47. goto Error;
  48. }
  49. m_Memory = (LPBYTE) MapViewOfFile(
  50. m_FileMapping,
  51. (ReadOnly) ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE,
  52. 0,0,
  53. 0);
  54. if(m_Memory == NULL) {
  55. fprintf(stderr,"Map view failed ! %X\n", GetLastError());
  56. goto Error;
  57. }
  58. if (*(WCHAR *) m_Memory != 0xFEFF) {
  59. fprintf(stderr,"This is not unicode text file !\n");
  60. goto Error;
  61. }
  62. m_Memory+=sizeof(WCHAR);
  63. m_FileSize -= sizeof(WCHAR);
  64. return TRUE;
  65. Error:
  66. bClose();
  67. return FALSE;
  68. }
  69. BOOL CFileMap::bClose()
  70. {
  71. if (m_Memory) {
  72. UnmapViewOfFile(m_Memory);
  73. m_Memory = NULL;
  74. }
  75. if (m_FileMapping) {
  76. CloseHandle(m_FileMapping);
  77. m_FileMapping = NULL;
  78. }
  79. if (m_FileHandle) {
  80. CloseHandle(m_FileHandle);
  81. m_FileHandle = NULL;
  82. }
  83. return TRUE;
  84. }