packio-simple

diff src/memmap.c @ 2:4767e7769c32

packio-simple has more chances to ever get done
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 09 Aug 2015 05:14:29 +0300
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/memmap.c	Sun Aug 09 05:14:29 2015 +0300
     1.3 @@ -0,0 +1,41 @@
     1.4 +#include <stdio.h>
     1.5 +#include <string.h>
     1.6 +#include <errno.h>
     1.7 +#include "memmap.h"
     1.8 +
     1.9 +#if defined(__unix__) || defined(__APPLE__)
    1.10 +#include <unistd.h>
    1.11 +#include <fcntl.h>
    1.12 +#include <sys/mman.h>
    1.13 +#include <sys/stat.h>
    1.14 +
    1.15 +int map_file(struct mmfile *mm, const char *fname)
    1.16 +{
    1.17 +	int fd;
    1.18 +	struct stat st;
    1.19 +
    1.20 +	if((fd = open(fname, O_RDONLY)) == -1) {
    1.21 +		fprintf(stderr, "map_file: failed to open %s: %s\n", fname, strerror(errno));
    1.22 +		return -1;
    1.23 +	}
    1.24 +	fstat(fd, &st);
    1.25 +
    1.26 +	if((mm->ptr = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == (void*)-1) {
    1.27 +		close(fd);
    1.28 +		fprintf(stderr, "map_file: failed to map file %s: %s\n", fname, strerror(errno));
    1.29 +		return -1;
    1.30 +	}
    1.31 +	mm->size = st.st_size;
    1.32 +
    1.33 +	close(fd);
    1.34 +	return 0;
    1.35 +}
    1.36 +
    1.37 +void unmap_file(struct mmfile *mm)
    1.38 +{
    1.39 +	munmap(mm->ptr, mm->size);
    1.40 +}
    1.41 +
    1.42 +#else
    1.43 +/* implement on win32 */
    1.44 +#endif