内存映射文件C ++

时间:2016-08-03 09:31:44

标签: c++ file winapi

请帮我阅读内存映射文件。我在下面的代码中打开文件。然后我想从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();

1 个答案:

答案 0 :(得分:5)

您可以像任何其他内存块一样访问它。这是一个打印解释为unsigned char s:

的字节的示例
unsigned char *mappedDataAsUChars = (unsigned char*)m_lpMapAddress;

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