readfilemap.c 1.8 KB

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