]> mj.ucw.cz Git - libucw.git/blob - lib/mmap.c
Initial version of SQL gathering utility gsql added.
[libucw.git] / lib / mmap.c
1 /*
2  *      Sherlock Library -- Mapping of Files
3  *
4  *      (c) 1999 Martin Mares <mj@ucw.cz>
5  */
6
7 #include "lib/lib.h"
8
9 #include <stdio.h>
10 #include <fcntl.h>
11 #include <unistd.h>
12 #include <sys/stat.h>
13 #include <sys/mman.h>
14
15 #ifndef MAP_FAILED
16 #warning System includes do not define MAP_FAILED.
17 #define MAP_FAILED ((void *)-1L)
18 #endif
19
20 void *
21 mmap_file(byte *name, unsigned *len, int writeable)
22 {
23   int fd = open(name, writeable ? O_RDWR : O_RDONLY);
24   struct stat st;
25   void *x;
26
27   if (fd < 0)
28     return NULL;
29   if (fstat(fd, &st) < 0)
30     x = NULL;
31   else
32     {
33       if (len)
34         *len = st.st_size;
35       if (st.st_size)
36         {
37           x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
38           if (x == MAP_FAILED)
39             x = NULL;
40         }
41       else      /* For empty file, we can return any non-zero address */
42         return "";
43     }
44   close(fd);
45   return x;
46 }
47
48 void
49 munmap_file(void *start, unsigned len)
50 {
51   munmap(start, len);
52 }