-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.cpp
More file actions
executable file
·39 lines (32 loc) · 816 Bytes
/
file.cpp
File metadata and controls
executable file
·39 lines (32 loc) · 816 Bytes
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
#include <cassert>
#include <cstdio>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
static long filesize(const char *filename)
{
FILE *f = fopen(filename, "rb");
assert(f != NULL);
fseek(f, 0, SEEK_SET);
long beg = ftell(f);
fseek(f, 0, SEEK_END);
long end = ftell(f);
fclose(f);
return end-beg;
}
const char *file_map(const char *filename, const char **end)
{
long size = filesize(filename);
int fd = open(filename, O_RDONLY);
assert(fd != -1);
const char *p = (const char *)mmap(NULL, size, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
assert(p != MAP_FAILED);
assert(close(fd) == 0);
*end = p + size;
return p;
}
void file_unmap(const char *p, const char *end)
{
long size = end - p;
assert(munmap((void *)p, size) == 0);
}