内存映射文件C++

Memory mapped file C++

本文关键字:C++ 文件 映射 内存      更新时间:2023-10-16

请帮助我读取内存映射文件。我在下面的代码中打开文件。然后我想读取从8到16的字节。我该怎么做?

// 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();

您可以像访问任何其他内存块一样访问它。下面是一个打印被解释为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;