grub2: bring back build of aros-side grub2 tools
[AROS.git] / workbench / libs / expat / xmlwf / readfilemap.c
blobbd32b934147148ac5081795b856c81de04a0947c
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 #ifdef __WATCOMC__
12 #ifndef __LINUX__
13 #include <io.h>
14 #else
15 #include <unistd.h>
16 #endif
17 #endif
19 #ifdef __BEOS__
20 #include <unistd.h>
21 #endif
23 #ifndef S_ISREG
24 #ifndef S_IFREG
25 #define S_IFREG _S_IFREG
26 #endif
27 #ifndef S_IFMT
28 #define S_IFMT _S_IFMT
29 #endif
30 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
31 #endif /* not S_ISREG */
33 #ifndef O_BINARY
34 #ifdef _O_BINARY
35 #define O_BINARY _O_BINARY
36 #else
37 #define O_BINARY 0
38 #endif
39 #endif
41 #include "filemap.h"
43 int
44 filemap(const char *name,
45 void (*processor)(const void *, size_t, const char *, void *arg),
46 void *arg)
48 size_t nbytes;
49 int fd;
50 int n;
51 struct stat sb;
52 void *p;
54 fd = open(name, O_RDONLY|O_BINARY);
55 if (fd < 0) {
56 perror(name);
57 return 0;
59 if (fstat(fd, &sb) < 0) {
60 perror(name);
61 close(fd);
62 return 0;
64 if (!S_ISREG(sb.st_mode)) {
65 fprintf(stderr, "%s: not a regular file\n", name);
66 close(fd);
67 return 0;
69 nbytes = sb.st_size;
70 /* malloc will return NULL with nbytes == 0, handle files with size 0 */
71 if (nbytes == 0) {
72 static const char c = '\0';
73 processor(&c, 0, name, arg);
74 close(fd);
75 return 1;
77 p = malloc(nbytes);
78 if (!p) {
79 fprintf(stderr, "%s: out of memory\n", name);
80 close(fd);
81 return 0;
83 n = read(fd, p, nbytes);
84 if (n < 0) {
85 perror(name);
86 free(p);
87 close(fd);
88 return 0;
90 if (n != nbytes) {
91 fprintf(stderr, "%s: read unexpected number of bytes\n", name);
92 free(p);
93 close(fd);
94 return 0;
96 processor(p, nbytes, name, arg);
97 free(p);
98 close(fd);
99 return 1;