]> mj.ucw.cz Git - libucw.git/blob - ucw/io-mmap.c
Merge branch 'dev-trans'
[libucw.git] / ucw / io-mmap.c
1 /*
2  *      UCW Library -- Mapping of Files
3  *
4  *      (c) 1999--2012 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "ucw/lib.h"
11 #include "ucw/io.h"
12
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/stat.h>
17 #include <sys/mman.h>
18
19 void *
20 mmap_file(const char *name, unsigned *len, int writeable)
21 {
22   int fd = open(name, writeable ? O_RDWR : O_RDONLY);
23   struct stat st;
24   void *x;
25
26   if (fd < 0)
27     die("open(%s): %m", name);
28   if (fstat(fd, &st) < 0)
29     die("fstat(%s): %m", name);
30   if (len)
31     *len = st.st_size;
32   if (st.st_size)
33     {
34       x = mmap(NULL, st.st_size, writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, fd, 0);
35       if (x == MAP_FAILED)
36         die("mmap(%s): %m", name);
37     }
38   else  /* For empty file, we can return any non-zero address */
39     x = "";
40   close(fd);
41   return x;
42 }
43
44 void
45 munmap_file(void *start, unsigned len)
46 {
47   munmap(start, len);
48 }