WIN32硬盘文件映射到内存CreateFileMapping
//内存申请物理页
HANDLE CreateFileMapping(
HANDLE hFile, //与文件句柄关联
LPSECURITY_ATTRIBUTES lpFileMappingAttributes, //NULL
DWORD flProtect, //访问保护类型
DWORD dwMaximumSizeHigh, //申请内存的大小的高32位
DWORD dwMaximumSizeLow, //申请内存大小的低32位
LPCTSTR lpName //内核对象名称,如果别的进程也用这块内存就需要用到的这个名称
);
//虚拟内存与物理页关联映射
LPVOID MapViewOfFile(
HANDLE hFileMappingObject, //内存申请的对象句柄
DWORD dwDesiredAccess, // 访问保护模式 范围小于等于 CreateFileMapping的
DWORD dwFileOffsetHigh,
DWORD dwFileOffsetLow,
DWORD dwNumberOfBytesToMap // 指定要映射的文件的字节数。如果dwNumberOfBytesToMap为零,则映射整个文件。
);
#include <stdio.h>
#include <windows.h>
int main()
{
//创建打开文件
HANDLE cFile = CreateFile("D:\\filterBufFile.txt",
GENERIC_READ | GENERIC_WRITE,
0,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
//内存申请物理页
HANDLE hMapFile = CreateFileMapping(cFile, NULL, PAGE_READWRITE, 0, 0, "共享映射");
//和虚拟地址映射
LPTSTR lpBuff = (LPTSTR)MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, 0);
//*(PDWORD)lpBuff = 0x12345678;
//getchar();
//读文件
printf("%p\n", lpBuff);
printf("%x\n", *(PDWORD)lpBuff);
printf("%x\n", *((PDWORD)lpBuff+1));
//写文件
*(PDWORD)lpBuff = 0x41414141;
printf("%x\n", *(PDWORD)lpBuff);
//getchar();
//强制刷新
//FlushViewOfFile(((PDWORD)lpBuff), 4);
//关闭映射
UnmapViewOfFile(lpBuff);
//关闭句柄
CloseHandle(hMapFile);
//关闭句柄
CloseHandle(cFile);
system("pause");
return(0);
}