- #include
- #include
- #include
- #include
- //这是一个对内存映射文件的demo程序,它打开一个文件,写入另一个文件中
- //1、调用CreateFile()创建一个内核文件对象,它指出了文件的路径和读取
- // 权限以及操作属性,后面的函数在读取属性上应该与之保持一致
- //2、调用CreateFileMapping()创建文件映射内核对象,它相当于指出
- // 了文件的物理存储的大小以及对象名,当大小设为0时,它表示与实际文件
- // 大小一致,在读时,大小应不大于实际大小,在写时,可大于实际大小
- //3、调用MapViewOfFile(),建立对映射文件的视图,也就是可以对文件的那
- // 部分进行操作,之后,可以象操作内存块一样操作文件
- //4、如果对文件进行了修改,需要及时更新,则调用FlushViewOfFile()
- //5、调用UnmapViewOfFile()取消映射
- int main(void)
- {
- HANDLE hFile;
- HANDLE hMapFile;
- HANDLE hFileWrite;
- HANDLE hMapFileWrite;
- LPBYTE lpMapView;
- LPBYTE lpMapViewWrite;
- int nFileSize;
- hFile = CreateFile("c:/calc.exe",GENERIC_READ,FILE_SHARE_READ,
- NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
- if(hFile == NULL)
- {
- printf("createfile is failed/n");
- return 0;
- }
- nFileSize = GetFileSize(hFile, NULL);
- hFileWrite = CreateFile("c:/calc1.exe",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,
- NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_ARCHIVE,NULL);
- if(hFileWrite == NULL)
- {
- printf("createfile is failed/n");
- return 0;
- }
- hMapFile = CreateFileMapping(hFile, // Current file handle.
- NULL, // Default security.
- PAGE_READONLY, // Read/write permission.
- 0, // Max. object size.
- 0, // Size of hFile.
- NULL);
- if(hMapFile == NULL)
- {
- printf("createfilemapping is failed/n");
- CloseHandle(hFile);
- return 0;
- }
- hMapFileWrite = CreateFileMapping(hFileWrite, // Current file handle.
- NULL, // Default security.
- PAGE_READWRITE, // Read/write permission.
- 0, // Max. object size.
- nFileSize, // Size of hFile.
- NULL);
- if(hMapFileWrite == NULL)
- {
- printf("createfilemapping is failed/n");
- CloseHandle(hFile);
- return 0;
- }
- lpMapView = (unsigned char*)MapViewOfFile(hMapFile,FILE_MAP_READ,NULL,NULL,0);
- if(lpMapView == NULL)
- {
- printf("MapView is failed/n");
- CloseHandle(hFile);
- CloseHandle(hMapFile);
- return 0;
- }
- lpMapViewWrite = (unsigned char*)MapViewOfFile(hMapFileWrite,FILE_MAP_WRITE,NULL,NULL,0);
- if(lpMapViewWrite == NULL)
- {
- printf("MapView is failed/n");
- CloseHandle(hFile);
- CloseHandle(hMapFile);
- return 0;
- }
- memcpy(lpMapViewWrite, lpMapView, nFileSize);
- FlushViewOfFile(lpMapViewWrite,nFileSize);
- UnmapViewOfFile(lpMapView);
- CloseHandle(hFile);
- CloseHandle(hMapFile);
- CloseHandle(hFileWrite);
- CloseHandle(hMapFileWrite);
- getchar();
- return 0;
- }
内存映射文件示例zz
最新推荐文章于 2021-05-24 23:39:04 发布