add mmap_readat

master
leitner 8 years ago
parent 82b17dbfe3
commit 5c999f4c62

@ -12,6 +12,9 @@ extern "C" {
* map in filesize and return pointer to map. */
const char* mmap_read(const char *filename,size_t* filesize);
/* like mmap_read but use openat instead of open */
const char* mmap_readat(const char *filename,size_t* filesize,int dirfd);
/* open file for writing, mmap whole file privately (copy on write),
* close file, write length of map in filesize and return pointer to
* map. */

@ -0,0 +1,23 @@
.TH mmap_readat 3
.SH NAME
mmap_readat \- memory map a file for reading
.SH SYNTAX
.B #include <mmap.h>
char* \fBmmap_readat\fP(const char* \fIfilename\fR,size_t* \fIfilesize\fR,int \fIdirfd\fR);
.SH DESCRIPTION
mmap_readat opens \fIfilename\fR for reading, maps the whole file into
memory, closes the file, writes the length of the file to \fIfilesize\fR
and returns a pointer to the mapped file.
If \fIfilename\fR is a relative path and \fIdirfd\fR is not -1,
\fIfilename\fR is interpreted relative to \fIdirfd\fR, which must be an
open directory.
The file is unmapped by the operating system if the process terminates.
It can also be manually unmapped by calling \fBmunmap\fR from
<sys/mman.h>.
If the file could not be opened or mapped, (void*)0 is returned.
.SH "SEE ALSO"
mmap_unmap(3)

@ -0,0 +1,36 @@
#define _POSIX_C_SOURCE 200809
#define _ATFILE_SOURCE
#include <sys/types.h>
#include <unistd.h>
#ifndef __MINGW32__
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#endif
#include "open.h"
#include "mmap.h"
extern const char* mmap_readat(const char* filename,size_t * filesize,int dirfd) {
#ifdef __MINGW32__
return 0;
#else
int fd=openat(dirfd,filename,O_RDONLY);
char *map;
if (fd>=0) {
register off_t o=lseek(fd,0,SEEK_END);
if (sizeof(off_t)!=sizeof(size_t) && o > (off_t)(size_t)-1) { close(fd); return 0; }
*filesize=(size_t)o;
if (o>0) {
map=mmap(0,*filesize,PROT_READ,MAP_SHARED,fd,0);
if (map==(char*)-1)
map=0;
} else
map="";
close(fd);
return map;
}
return 0;
#endif
}
Loading…
Cancel
Save