initial load of upstream version 1.06.32
[xmlrpc-c] / lib / expat / xmlwf / readfilemap.c
1 /*
2 Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
3 See the file copying.txt for copying permission.
4 */
5
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11
12 #ifndef S_ISREG
13 #ifndef S_IFREG
14 #define S_IFREG _S_IFREG
15 #endif
16 #ifndef S_IFMT
17 #define S_IFMT _S_IFMT
18 #endif
19 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
20 #endif /* not S_ISREG */
21
22 #ifndef O_BINARY
23 #ifdef _O_BINARY
24 #define O_BINARY _O_BINARY
25 #else
26 #define O_BINARY 0
27 #endif
28 #endif
29
30 int filemap(const char *name,
31             void (*processor)(const void *, size_t, const char *, void *arg),
32             void *arg)
33 {
34   size_t nbytes;
35   int fd;
36   int n;
37   struct stat sb;
38   void *p;
39
40   fd = open(name, O_RDONLY|O_BINARY);
41   if (fd < 0) {
42     perror(name);
43     return 0;
44   }
45   if (fstat(fd, &sb) < 0) {
46     perror(name);
47     return 0;
48   }
49   if (!S_ISREG(sb.st_mode)) {
50     fprintf(stderr, "%s: not a regular file\n", name);
51     return 0;
52   }
53   nbytes = sb.st_size;
54   p = malloc(nbytes);
55   if (!p) {
56     fprintf(stderr, "%s: out of memory\n", name);
57     return 0;
58   }
59   n = read(fd, p, nbytes);
60   if (n < 0) {
61     perror(name);
62     close(fd);
63     return 0;
64   }
65   if (n != nbytes) {
66     fprintf(stderr, "%s: read unexpected number of bytes\n", name);
67     close(fd);
68     return 0;
69   }
70   processor(p, nbytes, name, arg);
71   free(p);
72   close(fd);
73   return 1;
74 }