2016-08-03 164 views
-1

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

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

从这一个dublicate:[链接](http://stackoverflow.com/questions/9889557/mapping-large-files-using-mapviewoffile )。你有指针m_lpMapAddress,希望它是一个字节指针。将8个字节添加到指针并读取内存。这就是全部 – mrAtari

+0

@mrAtari如何添加8个字节? – ExiD

+0

m_lpMapAddress + = 8 – mrAtari

回答

4

您可以像访问其他内存块一样访问它。下面是打印解释为unsigned char小号那些字节的一个示例:

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

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

有更美丽的营养?如果我想在结构中读取字节呢? – ExiD

+0

@ExiD:A *“更美丽”*访问内存的方式?没有我知道的。更复杂?大概。但是,你不喜欢规范的方式来做到这一点? – IInspectable

+0

@ExiD您可以轻松完成'MyStruct * mappedDataAsMyStruct =(MyStruct *)m_lpMapAddress;'或类似的操作。注意对齐可能会使你的结构不能按照你想要的方式布局。 – immibis