-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.cpp
65 lines (53 loc) · 1.2 KB
/
file.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include "file.hpp"
#include "exceptions.hpp"
File::File( char *filename )
{
/* Open file */
fd = open( filename, O_RDONLY );
if ( fd < 0 ) {
perror( "open" );
throw UnixError( errno );
}
/* Get size of file */
struct stat thestat;
if ( fstat( fd, &thestat ) < 0 ) {
perror( "fstat" );
throw UnixError( errno );
}
filesize = thestat.st_size;
}
File::~File()
{
if ( close( fd ) < 0 ) {
perror( "close" );
throw UnixError( errno );
}
}
MapHandle *File::map( off_t offset, size_t len )
{
long page = sysconf( _SC_PAGE_SIZE );
off_t mmap_offset = offset & ~(page - 1);
uint8_t *mbuf = (uint8_t *)mmap( NULL, len + offset - mmap_offset,
PROT_READ,
MAP_PRIVATE, fd, mmap_offset );
if ( mbuf == MAP_FAILED ) {
perror( "mmap" );
throw UnixError( errno );
}
uint8_t *buf = mbuf + offset - mmap_offset;
return new MapHandle( buf, mbuf, len + offset - mmap_offset, len );
}
MapHandle::~MapHandle()
{
if ( munmap( mmap_buf, maplen ) < 0 ) {
perror( "munmap" );
throw UnixError( errno );
}
}