2
0

win32filemap.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
  3. See the file copying.txt for copying permission.
  4. */
  5. #define STRICT 1
  6. #define WIN32_LEAN_AND_MEAN 1
  7. #ifdef XML_UNICODE_WCHAR_T
  8. #ifndef XML_UNICODE
  9. #define XML_UNICODE
  10. #endif
  11. #endif
  12. #ifdef XML_UNICODE
  13. #define UNICODE
  14. #define _UNICODE
  15. #endif /* XML_UNICODE */
  16. #include <windows.h>
  17. #include <stdio.h>
  18. #include <tchar.h>
  19. #include "filemap.h"
  20. static void win32perror(const TCHAR *);
  21. int filemap(const TCHAR *name,
  22. void (*processor)(const void *, size_t, const TCHAR *, void *arg),
  23. void *arg)
  24. {
  25. HANDLE f;
  26. HANDLE m;
  27. DWORD size;
  28. DWORD sizeHi;
  29. void *p;
  30. f = CreateFile(name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
  31. FILE_FLAG_SEQUENTIAL_SCAN, NULL);
  32. if (f == INVALID_HANDLE_VALUE) {
  33. win32perror(name);
  34. return 0;
  35. }
  36. size = GetFileSize(f, &sizeHi);
  37. if (size == (DWORD)-1) {
  38. win32perror(name);
  39. return 0;
  40. }
  41. if (sizeHi) {
  42. _ftprintf(stderr, _T("%s: bigger than 2Gb\n"), name);
  43. return 0;
  44. }
  45. /* CreateFileMapping barfs on zero length files */
  46. if (size == 0) {
  47. static const char c = '\0';
  48. processor(&c, 0, name, arg);
  49. CloseHandle(f);
  50. return 1;
  51. }
  52. m = CreateFileMapping(f, NULL, PAGE_READONLY, 0, 0, NULL);
  53. if (m == NULL) {
  54. win32perror(name);
  55. CloseHandle(f);
  56. return 0;
  57. }
  58. p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
  59. if (p == NULL) {
  60. win32perror(name);
  61. CloseHandle(m);
  62. CloseHandle(f);
  63. return 0;
  64. }
  65. processor(p, size, name, arg);
  66. UnmapViewOfFile(p);
  67. CloseHandle(m);
  68. CloseHandle(f);
  69. return 1;
  70. }
  71. static
  72. void win32perror(const TCHAR *s)
  73. {
  74. LPVOID buf;
  75. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  76. NULL,
  77. GetLastError(),
  78. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  79. (LPTSTR) &buf,
  80. 0,
  81. NULL)) {
  82. _ftprintf(stderr, _T("%s: %s"), s, buf);
  83. fflush(stderr);
  84. LocalFree(buf);
  85. }
  86. else
  87. _ftprintf(stderr, _T("%s: unknown Windows error\n"), s);
  88. }