1104349Sphk/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
2104349Sphk   See the file COPYING for copying permission.
3104349Sphk*/
4104349Sphk
5104349Sphk#include <sys/types.h>
6104349Sphk#include <sys/mman.h>
7104349Sphk#include <sys/stat.h>
8104349Sphk#include <fcntl.h>
9104349Sphk#include <errno.h>
10104349Sphk#include <string.h>
11104349Sphk#include <stdio.h>
12104349Sphk#include <unistd.h>
13104349Sphk
14104349Sphk#ifndef MAP_FILE
15104349Sphk#define MAP_FILE 0
16104349Sphk#endif
17104349Sphk
18104349Sphk#include "filemap.h"
19104349Sphk
20104349Sphkint
21104349Sphkfilemap(const char *name,
22104349Sphk        void (*processor)(const void *, size_t, const char *, void *arg),
23104349Sphk        void *arg)
24104349Sphk{
25104349Sphk  int fd;
26104349Sphk  size_t nbytes;
27104349Sphk  struct stat sb;
28104349Sphk  void *p;
29104349Sphk
30104349Sphk  fd = open(name, O_RDONLY);
31104349Sphk  if (fd < 0) {
32104349Sphk    perror(name);
33104349Sphk    return 0;
34104349Sphk  }
35104349Sphk  if (fstat(fd, &sb) < 0) {
36104349Sphk    perror(name);
37104349Sphk    close(fd);
38104349Sphk    return 0;
39104349Sphk  }
40104349Sphk  if (!S_ISREG(sb.st_mode)) {
41104349Sphk    close(fd);
42104349Sphk    fprintf(stderr, "%s: not a regular file\n", name);
43104349Sphk    return 0;
44104349Sphk  }
45104349Sphk
46104349Sphk  nbytes = sb.st_size;
47178848Scokane  /* mmap fails for zero length files */
48178848Scokane  if (nbytes == 0) {
49178848Scokane    static const char c = '\0';
50178848Scokane    processor(&c, 0, name, arg);
51178848Scokane    close(fd);
52178848Scokane    return 1;
53178848Scokane  }
54104349Sphk  p = (void *)mmap((caddr_t)0, (size_t)nbytes, PROT_READ,
55104349Sphk                   MAP_FILE|MAP_PRIVATE, fd, (off_t)0);
56104349Sphk  if (p == (void *)-1) {
57104349Sphk    perror(name);
58104349Sphk    close(fd);
59104349Sphk    return 0;
60104349Sphk  }
61104349Sphk  processor(p, nbytes, name, arg);
62104349Sphk  munmap((caddr_t)p, nbytes);
63104349Sphk  close(fd);
64104349Sphk  return 1;
65104349Sphk}
66