-
Notifications
You must be signed in to change notification settings - Fork 2
/
memfile.h
54 lines (41 loc) · 1.31 KB
/
memfile.h
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
// Elmo Trolla, 2019
// License: pick one - public domain / UNLICENSE (https://www.unlicense.org) / MIT (https://opensource.org/licenses/MIT).
#pragma once
//
// memory-mapped file interface for windows.
//
// MemFile f("data.bin");
// printf("last byte: %i", (int)f.buf[f.file_size-1]);
//
#include "windows.h"
// memorymapped file read
struct MemFile
{
char* buf;
uint64_t file_size;
MemFile(char* filename)
{
buf = NULL;
fileHandle = NULL;
mapFile = NULL;
file_size = 0;
fileHandle = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (!fileHandle) return;
if (!GetFileSizeEx(fileHandle, (PLARGE_INTEGER)&file_size)) return;
//mapFile = OpenFileMapping(FILE_MAP_READ, FALSE, filename);
mapFile = CreateFileMapping(fileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
//mapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READONLY, 0, 0, filename);
if (!mapFile) return;
buf = (char*)MapViewOfFile(mapFile, FILE_MAP_READ, 0, 0, 0);
//buf = (LPTSTR) MapViewOfFile(mapFile, FILE_MAP_READ, 0, 0, BUF_SIZE);
if (!buf) CloseHandle(mapFile);
}
~MemFile() {
if (buf) UnmapViewOfFile(buf);
if (mapFile) CloseHandle(mapFile);
if (fileHandle) CloseHandle(fileHandle);
}
private:
HANDLE fileHandle;
HANDLE mapFile;
};