内存映射文件示例

内存映射文件示例

 //获取当前操作系统的分配粒度
 SYSTEM_INFO sinf;
 GetSystemInfo(&sinf);
 DWORD dwAllocationGranularity = sinf.dwAllocationGranularity;

 //GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ这两个参数如果设置错误将导致错误
 HANDLE hFile = CreateFile("join", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ,
  NULL, CREATE_ALWAYS, FILE_FLAG_SEQUENTIAL_SCAN, NULL);

 //PAGE_READWRITE这个属性必须和GENERIC_WRITE | GENERIC_READ属性对应
 HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0,
  0x4000000, NULL);
 
 CloseHandle(hFile);

 __int64 qwFileSize = 0x4000000;
 __int64 qwFileOffset = 0;
 __int64 T = 600 * sinf.dwAllocationGranularity;
 DWORD dwBytesInBlock = 1000 * sinf.dwAllocationGranularity;

 //qwFileOffset>>32 取64位高位
 //qwFileOffset&0xFFFFFFFF 取64位低位
 //FILE_MAP_ALL_ACCESS这个属性与CreateFile和CreateFileMapping属性必须匹配
 PBYTE pbFile = (PBYTE)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS,
  (DWORD)(qwFileOffset>>32), (DWORD)(qwFileOffset&0xFFFFFFFF), dwBytesInBlock);

 memcpy(pbFile, "123", 3);
 char temp[3];
 memcpy(temp, pbFile, 3);

 UnmapViewOfFile(pbFile);

你可能感兴趣的:(内存映射文件示例)