readfilemap.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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/stat.h>
  6. #include <fcntl.h>
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <unistd.h>
  10. #ifdef __WATCOMC__
  11. #ifndef __LINUX__
  12. #include <io.h>
  13. #else
  14. #include <unistd.h>
  15. #endif
  16. #endif
  17. #ifdef __BEOS__
  18. #include <unistd.h>
  19. #endif
  20. #ifndef S_ISREG
  21. #ifndef S_IFREG
  22. #define S_IFREG _S_IFREG
  23. #endif
  24. #ifndef S_IFMT
  25. #define S_IFMT _S_IFMT
  26. #endif
  27. #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  28. #endif /* not S_ISREG */
  29. #ifndef O_BINARY
  30. #ifdef _O_BINARY
  31. #define O_BINARY _O_BINARY
  32. #else
  33. #define O_BINARY 0
  34. #endif
  35. #endif
  36. #include "filemap.h"
  37. int
  38. filemap(const char *name,
  39. void (*processor)(const void *, size_t, const char *, void *arg),
  40. void *arg)
  41. {
  42. size_t nbytes;
  43. int fd;
  44. int n;
  45. struct stat sb;
  46. void *p;
  47. fd = open(name, O_RDONLY|O_BINARY);
  48. if (fd < 0) {
  49. perror(name);
  50. return 0;
  51. }
  52. if (fstat(fd, &sb) < 0) {
  53. perror(name);
  54. return 0;
  55. }
  56. if (!S_ISREG(sb.st_mode)) {
  57. fprintf(stderr, "%s: not a regular file\n", name);
  58. return 0;
  59. }
  60. nbytes = sb.st_size;
  61. /* malloc will return NULL with nbytes == 0, handle files with size 0 */
  62. if (nbytes == 0) {
  63. static const char c = '\0';
  64. processor(&c, 0, name, arg);
  65. close(fd);
  66. return 1;
  67. }
  68. p = malloc(nbytes);
  69. if (!p) {
  70. fprintf(stderr, "%s: out of memory\n", name);
  71. close(fd);
  72. return 0;
  73. }
  74. n = read(fd, p, nbytes);
  75. if (n < 0) {
  76. perror(name);
  77. free(p);
  78. close(fd);
  79. return 0;
  80. }
  81. if (n != nbytes) {
  82. fprintf(stderr, "%s: read unexpected number of bytes\n", name);
  83. free(p);
  84. close(fd);
  85. return 0;
  86. }
  87. processor(p, nbytes, name, arg);
  88. free(p);
  89. close(fd);
  90. return 1;
  91. }