ExiD ExiD - 3 months ago 33
C++ Question

Memory mapped file C++

please help me with reading memory mapped file. I open file in code below. And then i want to read bytes from 8 to 16. How can i do that?

// 0. Handle or create and handle file
m_hFile = CreateFile(file_path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (m_hFile == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
m_hFile = createNewFile(file_path.c_str());
}
else throw GetLastError();
}

// 1. Create a file mapping object for the file
m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (m_hMapFile == NULL) throw GetLastError();

// 2. Map the view.
m_lpMapAddress = MapViewOfFile(m_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
// to map
if (m_lpMapAddress == NULL) throw GetLastError();

Answer

You can access it like any other memory block. Here's an example that prints those bytes interpreted as unsigned chars:

unsigned char *mappedDataAsUChars = (unsigned char*)m_lpMapAddress;

for(int k = 8; k < 16; k++)
    std::cout << "Byte at " << k << " is " << mappedDataAsUChars[k] << std::endl;
Comments