win32filemap.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
  2. See the file COPYING for copying permission.
  3. */
  4. #define STRICT 1
  5. #define WIN32_LEAN_AND_MEAN 1
  6. #ifdef XML_UNICODE_WCHAR_T
  7. #ifndef XML_UNICODE
  8. #define XML_UNICODE
  9. #endif
  10. #endif
  11. #ifdef XML_UNICODE
  12. #define UNICODE
  13. #define _UNICODE
  14. #endif /* XML_UNICODE */
  15. #include <windows.h>
  16. #include <stdio.h>
  17. #include <tchar.h>
  18. #include "filemap.h"
  19. static void win32perror(const TCHAR *);
  20. int
  21. 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. CloseHandle(f);
  40. return 0;
  41. }
  42. if (sizeHi || (size > XML_MAX_CHUNK_LEN)) {
  43. CloseHandle(f);
  44. return 2; /* Cannot be passed to XML_Parse in one go */
  45. }
  46. /* CreateFileMapping barfs on zero length files */
  47. if (size == 0) {
  48. static const char c = '\0';
  49. processor(&c, 0, name, arg);
  50. CloseHandle(f);
  51. return 1;
  52. }
  53. m = CreateFileMapping(f, NULL, PAGE_READONLY, 0, 0, NULL);
  54. if (m == NULL) {
  55. win32perror(name);
  56. CloseHandle(f);
  57. return 0;
  58. }
  59. p = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
  60. if (p == NULL) {
  61. win32perror(name);
  62. CloseHandle(m);
  63. CloseHandle(f);
  64. return 0;
  65. }
  66. processor(p, size, name, arg);
  67. UnmapViewOfFile(p);
  68. CloseHandle(m);
  69. CloseHandle(f);
  70. return 1;
  71. }
  72. static void
  73. win32perror(const TCHAR *s)
  74. {
  75. LPVOID buf;
  76. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
  77. | FORMAT_MESSAGE_FROM_SYSTEM,
  78. NULL,
  79. GetLastError(),
  80. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  81. (LPTSTR) &buf,
  82. 0,
  83. NULL)) {
  84. _ftprintf(stderr, _T("%s: %s"), s, buf);
  85. fflush(stderr);
  86. LocalFree(buf);
  87. }
  88. else
  89. _ftprintf(stderr, _T("%s: unknown Windows error\n"), s);
  90. }