mapfile.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #ifndef _MAPFILE_HPP_
  2. #define _MAPFILE_HPP_
  3. #ifdef HAVE_CONFIG_H
  4. # include "config.h"
  5. #endif
  6. #ifdef HAVE_MMAP
  7. # include <sys/types.h>
  8. # include <fcntl.h>
  9. # include <sys/mman.h>
  10. #endif
  11. #ifdef _WIN32
  12. # include <windows.h>
  13. #endif
  14. #include <glib.h>
  15. class MapFile
  16. {
  17. public:
  18. MapFile(void) :
  19. data(NULL),
  20. #ifdef HAVE_MMAP
  21. mmap_fd( -1)
  22. #elif defined(_WIN32)
  23. hFile(0),
  24. hFileMap(0)
  25. #endif
  26. {
  27. }
  28. ~MapFile();
  29. bool open(const char *file_name, unsigned long file_size);
  30. inline gchar *begin(void)
  31. {
  32. return data;
  33. }
  34. private:
  35. char *data;
  36. unsigned long size;
  37. #ifdef HAVE_MMAP
  38. int mmap_fd;
  39. #elif defined(_WIN32)
  40. HANDLE hFile;
  41. HANDLE hFileMap;
  42. #endif
  43. };
  44. inline bool MapFile::open(const char *file_name, unsigned long file_size)
  45. {
  46. size = file_size;
  47. #ifdef HAVE_MMAP
  48. if ((mmap_fd = ::open(file_name, O_RDONLY)) < 0)
  49. {
  50. //g_print("Open file %s failed!\n",fullfilename);
  51. return false;
  52. }
  53. data = (gchar *)mmap( NULL, file_size, PROT_READ, MAP_SHARED, mmap_fd, 0);
  54. if ((void *)data == (void *)( -1))
  55. {
  56. //g_print("mmap file %s failed!\n",idxfilename);
  57. data = NULL;
  58. return false;
  59. }
  60. #elif defined( _WIN32)
  61. #ifdef UNICODE
  62. gunichar2 *fn = g_utf8_to_utf16(file_name, -1, NULL, NULL, NULL);
  63. #else // UNICODE
  64. gchar *fn = file_name;
  65. #endif // UNICODE
  66. hFile = CreateFile(fn, GENERIC_READ, 0, NULL, OPEN_ALWAYS,
  67. FILE_ATTRIBUTE_NORMAL, 0);
  68. #ifdef UNICODE
  69. g_free(fn);
  70. #endif // UNICODE
  71. hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0,
  72. file_size, NULL);
  73. data = (gchar *)MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, file_size);
  74. #else // defined( _WIN32)
  75. gsize read_len;
  76. if (!g_file_get_contents(file_name, &data, &read_len, NULL))
  77. return false;
  78. if (read_len != file_size)
  79. return false;
  80. #endif
  81. return true;
  82. }
  83. inline MapFile::~MapFile()
  84. {
  85. if (!data)
  86. return ;
  87. #ifdef HAVE_MMAP
  88. munmap(data, size);
  89. close(mmap_fd);
  90. #else
  91. # ifdef _WIN32
  92. UnmapViewOfFile(data);
  93. CloseHandle(hFileMap);
  94. CloseHandle(hFile);
  95. # else
  96. g_free(data);
  97. # endif
  98. #endif
  99. }
  100. #endif//!_MAPFILE_HPP_