1/*
2The contents of this file are subject to the Mozilla Public License
3Version 1.0 (the "License"); you may not use this file except in
4compliance with the License. You may obtain a copy of the License at
5http://www.mozilla.org/MPL/
6
7Software distributed under the License is distributed on an "AS IS"
8basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
9License for the specific language governing rights and limitations
10under the License.
11
12The Original Code is expat.
13
14The Initial Developer of the Original Code is James Clark.
15Portions created by James Clark are Copyright (C) 1998
16James Clark. All Rights Reserved.
17
18Contributor(s):
19*/
20
21#include <sys/types.h>
22#include <sys/stat.h>
23#include <fcntl.h>
24#include <stdlib.h>
25#include <stdio.h>
26
27#ifndef S_ISREG
28#ifndef S_IFREG
29#define S_IFREG _S_IFREG
30#endif
31#ifndef S_IFMT
32#define S_IFMT _S_IFMT
33#endif
34#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
35#endif /* not S_ISREG */
36
37#ifndef O_BINARY
38#ifdef _O_BINARY
39#define O_BINARY _O_BINARY
40#else
41#define O_BINARY 0
42#endif
43#endif
44
45int filemap(const char *name,
46	    void (*processor)(const void *, size_t, const char *, void *arg),
47	    void *arg)
48{
49  size_t nbytes;
50  int fd;
51  int n;
52  struct stat sb;
53  void *p;
54
55  fd = open(name, O_RDONLY|O_BINARY);
56  if (fd < 0) {
57    perror(name);
58    return 0;
59  }
60  if (fstat(fd, &sb) < 0) {
61    perror(name);
62    return 0;
63  }
64  if (!S_ISREG(sb.st_mode)) {
65    fprintf(stderr, "%s: not a regular file\n", name);
66    return 0;
67  }
68  nbytes = sb.st_size;
69  p = malloc(nbytes);
70  if (!p) {
71    fprintf(stderr, "%s: out of memory\n", name);
72    return 0;
73  }
74  n = read(fd, p, nbytes);
75  if (n < 0) {
76    perror(name);
77    close(fd);
78    return 0;
79  }
80  if (n != nbytes) {
81    fprintf(stderr, "%s: read unexpected number of bytes\n", name);
82    close(fd);
83    return 0;
84  }
85  processor(p, nbytes, name, arg);
86  free(p);
87  close(fd);
88  return 1;
89}
90