unixfilemap.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. nbytes = sb.st_size;
  41. /* mmap fails for zero length files */
  42. if (nbytes == 0) {
  43. static const char c = '\0';
  44. processor(&c, 0, name, arg);
  45. close(fd);
  46. return 1;
  47. }
  48. p = (void *)mmap((caddr_t)0, (size_t)nbytes, PROT_READ,
  49. MAP_FILE|MAP_PRIVATE, fd, (off_t)0);
  50. if (p == (void *)-1) {
  51. perror(name);
  52. close(fd);
  53. return 0;
  54. }
  55. processor(p, nbytes, name, arg);
  56. munmap((caddr_t)p, nbytes);
  57. close(fd);
  58. return 1;
  59. }