]> mj.ucw.cz Git - libucw.git/blob - lib/mmap.c
23f69e6e36319d44426303435a9489a554f955fc
[libucw.git] / lib / mmap.c
1 /*
2  *      Sherlock Library -- Mapping of Files
3  *
4  *      (c) 1999 Martin Mares, <mj@atrey.karlin.mff.cuni.cz>
5  */
6
7 #include <stdio.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <sys/stat.h>
11 #include <sys/mman.h>
12
13 #include "lib.h"
14
15 #ifndef MAP_FAILED
16 #define MAP_FAILED ((void *)-1L)
17 #endif
18
19 void *
20 mmap_file(byte *name, unsigned *len)
21 {
22   int fd = open(name, O_RDONLY);
23   struct stat st;
24   void *x;
25
26   if (fd < 0)
27     return NULL;
28   if (fstat(fd, &st) < 0)
29     x = NULL;
30   else
31     {
32       if (len)
33         *len = st.st_size;
34       x = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
35       if (x == MAP_FAILED)
36         x = NULL;
37     }
38   close(fd);
39   return x;
40 }