【发布时间】:2016-12-08 22:43:20
【问题描述】:
请帮助我阅读内存映射文件。我在下面的代码中打开文件。然后我想从 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();
【问题讨论】:
-
是来自这个的副本:link。您有指针 m_lpMapAddress,希望它是一个字节指针。将 8 个字节添加到指针并读取内存。就是这样
-
@mrAtari 如何添加 8 个字节?
-
m_lpMapAddress +=8
-
@mrAtari:那行不通。
MapViewOfFile返回void*。如果对m_lpMapAddress的赋值没有强制转换,那么它的类型也必须是void*。您不能在void*上使用operator+=。您必须先转换为特定类型(unsigned char表示字节)。 -
你听说过指针转换吗? char* 光标 = (char*)m_lpMapAddress;光标+=8;