unixfilemap.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
  2. See the file COPYING for copying permission.
  3. */
  4. #include <sys/types.h>
  5. #include <sys/mman.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #ifndef MAP_FILE
  13. #define MAP_FILE 0
  14. #endif
  15. #include "filemap.h"
  16. int
  17. filemap(const char *name,
  18. void (*processor)(const void *, size_t, const char *, void *arg),
  19. void *arg)
  20. {
  21. int fd;
  22. size_t nbytes;
  23. struct stat sb;
  24. void *p;
  25. fd = open(name, O_RDONLY);
  26. if (fd < 0) {
  27. perror(name);
  28. return 0;
  29. }
  30. if (fstat(fd, &sb) < 0) {
  31. perror(name);
  32. close(fd);
  33. return 0;
  34. }
  35. if (!S_ISREG(sb.st_mode)) {
  36. close(fd);
  37. fprintf(stderr, "%s: not a regular file\n", name);
  38. return 0;
  39. }
  40. if (sb.st_size > XML_MAX_CHUNK_LEN) {
  41. close(fd);
  42. return 2; /* Cannot be passed to XML_Parse in one go */
  43. }
  44. nbytes = sb.st_size;
  45. /* mmap fails for zero length files */
  46. if (nbytes == 0) {
  47. static const char c = '\0';
  48. processor(&c, 0, name, arg);
  49. close(fd);
  50. return 1;
  51. }
  52. p = (void *)mmap((void *)0, (size_t)nbytes, PROT_READ,
  53. MAP_FILE|MAP_PRIVATE, fd, (off_t)0);
  54. if (p == (void *)-1) {
  55. perror(name);
  56. close(fd);
  57. return 0;
  58. }
  59. processor(p, nbytes, name, arg);
  60. munmap((void *)p, nbytes);
  61. close(fd);
  62. return 1;
  63. }