unixfilemap.c 1.1 KB

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