1/*
2The contents of this file are subject to the Mozilla Public License
3Version 1.1 (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, 1999
16James Clark. All Rights Reserved.
17
18Contributor(s):
19
20Alternatively, the contents of this file may be used under the terms
21of the GNU General Public License (the "GPL"), in which case the
22provisions of the GPL are applicable instead of those above.  If you
23wish to allow use of your version of this file only under the terms of
24the GPL and not to allow others to use your version of this file under
25the MPL, indicate your decision by deleting the provisions above and
26replace them with the notice and other provisions required by the
27GPL. If you do not delete the provisions above, a recipient may use
28your version of this file under either the MPL or the GPL.
29*/
30
31#include <sys/types.h>
32#include <sys/stat.h>
33#include <fcntl.h>
34#include <stdlib.h>
35#include <stdio.h>
36
37#ifndef S_ISREG
38#ifndef S_IFREG
39#define S_IFREG _S_IFREG
40#endif
41#ifndef S_IFMT
42#define S_IFMT _S_IFMT
43#endif
44#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
45#endif /* not S_ISREG */
46
47#ifndef O_BINARY
48#ifdef _O_BINARY
49#define O_BINARY _O_BINARY
50#else
51#define O_BINARY 0
52#endif
53#endif
54
55
56#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
57extern int open (const char* path, int mode);
58extern int read (int fd, void* buf, size_t count);
59extern int close (int fd);
60#endif
61
62
63int filemap(const char *name,
64	    void (*processor)(const void *, size_t, const char *, void *arg),
65	    void *arg)
66{
67  size_t nbytes;
68  int fd;
69  int n;
70  struct stat sb;
71  void *p;
72
73  fd = open(name, O_RDONLY|O_BINARY);
74  if (fd < 0) {
75    perror(name);
76    return 0;
77  }
78  if (fstat(fd, &sb) < 0) {
79    perror(name);
80    return 0;
81  }
82  if (!S_ISREG(sb.st_mode)) {
83    fprintf(stderr, "%s: not a regular file\n", name);
84    return 0;
85  }
86  nbytes = sb.st_size;
87  p = malloc(nbytes);
88  if (!p) {
89    fprintf(stderr, "%s: out of memory\n", name);
90    return 0;
91  }
92  n = read(fd, p, nbytes);
93  if (n < 0) {
94    perror(name);
95    close(fd);
96    return 0;
97  }
98  if ((size_t) n != nbytes) {
99    fprintf(stderr, "%s: read unexpected number of bytes\n", name);
100    close(fd);
101    return 0;
102  }
103  processor(p, nbytes, name, arg);
104  free(p);
105  close(fd);
106  return 1;
107}
108