繁体   English   中英

内存映射文件C ++

[英]Memory mapped file C++

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM