HANDLE hFile = NULL;
HANDLE hFileMap = NULL;
const viewmapsize = 8 * 1024 * 1024;//8m
DWORD highsize,lowsize,fileoffsetlow,fileoffsethigh,mapsize;
_int64 filesize,offset,remain;
int dwError;
do {
//打开文件
hFile= CreateFile("g:\\1289527402.png",
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if ( hFile == INVALID_HANDLE_VALUE )
{
CString cs;
cs.Format("打开文件失败:%d",GetLastError());
AfxMessageBox(cs);
break;
}
lowsize = GetFileSize(hFile,&highsize);
if ( lowsize == 0xFFFFFFFF && ( dwError = GetLastError() ) != NO_ERROR )
{
CString cs;
cs.Format("获取文件大小失败:%d",dwError);
AfxMessageBox(cs);
break;
}
//文件大小
filesize = highsize<<32 | lowsize;
hFileMap = CreateFileMapping(hFile,NULL,
PAGE_READONLY,
highsize,
lowsize,
NULL);
if ( hFileMap == NULL )
{
CString cs;
cs.Format("建立CreateFileMapping失败:%d",GetLastError());
AfxMessageBox(cs);
break;
}
offset = 0;
mapsize = (int)(filesize > viewmapsize ? viewmapsize : filesize);
fileoffsethigh = (int)(offset >> 32);
fileoffsetlow = (int)(offset / viewmapsize * viewmapsize);
LPVOID lpmap;
while ( filesize > offset && ( lpmap = MapViewOfFile(hFileMap,FILE_MAP_READ,fileoffsethigh,fileoffsetlow,mapsize) ) != NULL )
{
offset += mapsize;
remain = filesize - offset;
mapsize = (int)(remain > viewmapsize ? viewmapsize : remain);
fileoffsethigh = (int)(offset >> 32);
fileoffsetlow = (int)(offset);
UnmapViewOfFile(lpmap);
}
if ( lpmap == NULL )
{
CString cs;
cs.Format("建立MapViewOfFile失败:%d",GetLastError());
AfxMessageBox(cs);
break;
}
else
UnmapViewOfFile(lpmap);
if ( filesize == offset )
AfxMessageBox("映射文件结束");
}while (0);
if ( hFileMap )
CloseHandle(hFileMap);
if (hFile)
CloseHandle(hFile);
文件映射操作实例
最新推荐文章于 2022-03-24 18:14:49 发布