readfilemap.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/stat.h>
  7. #include <fcntl.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #ifndef S_ISREG
  11. #ifndef S_IFREG
  12. #define S_IFREG _S_IFREG
  13. #endif
  14. #ifndef S_IFMT
  15. #define S_IFMT _S_IFMT
  16. #endif
  17. #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  18. #endif /* not S_ISREG */
  19. #ifndef O_BINARY
  20. #ifdef _O_BINARY
  21. #define O_BINARY _O_BINARY
  22. #else
  23. #define O_BINARY 0
  24. #endif
  25. #endif
  26. int filemap(const char *name,
  27. void (*processor)(const void *, size_t, const char *, void *arg),
  28. void *arg)
  29. {
  30. size_t nbytes;
  31. int fd;
  32. int n;
  33. struct stat sb;
  34. void *p;
  35. fd = open(name, O_RDONLY|O_BINARY);
  36. if (fd < 0) {
  37. perror(name);
  38. return 0;
  39. }
  40. if (fstat(fd, &sb) < 0) {
  41. perror(name);
  42. return 0;
  43. }
  44. if (!S_ISREG(sb.st_mode)) {
  45. fprintf(stderr, "%s: not a regular file\n", name);
  46. return 0;
  47. }
  48. nbytes = sb.st_size;
  49. p = malloc(nbytes);
  50. if (!p) {
  51. fprintf(stderr, "%s: out of memory\n", name);
  52. return 0;
  53. }
  54. n = read(fd, p, nbytes);
  55. if (n < 0) {
  56. perror(name);
  57. close(fd);
  58. return 0;
  59. }
  60. if (n != nbytes) {
  61. fprintf(stderr, "%s: read unexpected number of bytes\n", name);
  62. close(fd);
  63. return 0;
  64. }
  65. processor(p, nbytes, name, arg);
  66. free(p);
  67. close(fd);
  68. return 1;
  69. }