bux API Reference
1.12.6
Static library of whatever are seen required in general purpose but not directly supported from Modern C++. Or whatever reusable originated from my side projects.
Toggle main menu visibility
Loading...
Searching...
No Matches
src
FileAsMem.cpp
Go to the documentation of this file.
1
#include "
FileAsMem.h
"
2
#ifndef _WIN32
3
#include <sys/mman.h>
// mmap(), munmap()
4
#include <fcntl.h>
// open()
5
#include <unistd.h>
// lseek()
6
#endif
7
#include <stdexcept>
// std::runtime_error
8
9
namespace
bux
{
10
11
C_FileAsMemory::C_FileAsMemory
(
const
std::filesystem::path& path)
12
{
13
#ifdef _WIN32
14
const
auto
hFile = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ,
nullptr
, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
nullptr
);
15
if
(hFile == INVALID_HANDLE_VALUE)
16
throw
std::runtime_error{
"Failed to open \""
+ path.string() +
"\" for read-only"
};
17
18
m_handle = CreateFileMappingW(hFile,
nullptr
, PAGE_READONLY, 0, 0,
nullptr
);
19
CloseHandle(hFile);
20
if
(!m_handle)
21
throw
std::runtime_error{
"Failed to create file mapping"
};
22
23
m_data =
static_cast<
char
*
>
(MapViewOfFile(m_handle, FILE_MAP_READ, 0, 0, 0));
24
if
(!m_data)
25
CloseHandle(m_handle);
26
#else
27
m_fd = open(path.c_str(), O_RDONLY);
28
if
(m_fd == -1)
29
throw
std::runtime_error{
"Failed to open \""
+ path.string() +
"\" for read-only"
};
30
31
m_bytes = (size_t)lseek(m_fd, 0, SEEK_END);
32
auto
data
= mmap(
nullptr
, m_bytes, PROT_READ, MAP_PRIVATE, m_fd, 0);
33
if
(
data
!= MAP_FAILED)
34
m_data =
static_cast<
char
*
>
(
data
);
35
else
36
close(m_fd);
37
#endif
38
}
39
40
C_FileAsMemory::~C_FileAsMemory
()
41
{
42
if
(m_data)
43
{
44
#ifdef _WIN32
45
UnmapViewOfFile(m_data);
46
CloseHandle(m_handle);
47
#else
48
munmap(m_data, m_bytes);
49
close(m_fd);
50
#endif
51
}
52
}
53
54
}
// namespace bux
FileAsMem.h
bux::C_FileAsMemory::data
const char * data() const
Definition
FileAsMem.h:16
bux::C_FileAsMemory::C_FileAsMemory
C_FileAsMemory(const std::filesystem::path &path)
Definition
FileAsMem.cpp:11
bux::C_FileAsMemory::~C_FileAsMemory
~C_FileAsMemory()
Definition
FileAsMem.cpp:40
bux
THE common namespace of bux library.
Definition
AtomiX.cpp:3
Generated by
1.18.0