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/mman.h> 23#include <sys/stat.h> 24#include <fcntl.h> 25#include <errno.h> 26#include <string.h> 27#include <stdio.h> 28 29#ifndef MAP_FILE 30#define MAP_FILE 0 31#endif 32 33#include "filemap.h" 34 35int filemap(const char *name, 36 void (*processor)(const void *, size_t, const char *, void *arg), 37 void *arg) 38{ 39 int fd; 40 size_t nbytes; 41 struct stat sb; 42 void *p; 43 44 fd = open(name, O_RDONLY); 45 if (fd < 0) { 46 perror(name); 47 return 0; 48 } 49 if (fstat(fd, &sb) < 0) { 50 perror(name); 51 close(fd); 52 return 0; 53 } 54 if (!S_ISREG(sb.st_mode)) { 55 close(fd); 56 fprintf(stderr, "%s: not a regular file\n", name); 57 return 0; 58 } 59 60 nbytes = sb.st_size; 61 p = (void *)mmap((caddr_t)0, (size_t)nbytes, PROT_READ, 62 MAP_FILE|MAP_PRIVATE, fd, (off_t)0); 63 if (p == (void *)-1) { 64 perror(name); 65 close(fd); 66 return 0; 67 } 68 processor(p, nbytes, name, arg); 69 munmap((caddr_t)p, nbytes); 70 close(fd); 71 return 1; 72} 73