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