bool DisposeBigFile( const string& strFilePath )
{
// 创建文件对象
bool bRet = false;
HANDLE hFile = INVALID_HANDLE_VALUE;
HANDLE hFileMap = NULL;
do
{
hFile = CreateFile(strFilePath.c_str(), GENERIC_READ | GENERIC_WRITE,0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
TRACE("创建文件对象失败,错误代码:%d\r\n", GetLastError());
break;
}
// 得到系统分配粒度
SYSTEM_INFO stSysInfo;
GetSystemInfo(&stSysInfo);
DWORD dwGran = stSysInfo.dwAllocationGranularity;
// 得到文件尺寸
DWORD dwFileSizeHigh;
__int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
qwFileSize |= (((__int64)dwFileSizeHigh) << 32);
if(0 == qwFileSize)
{
bRet = true;
break;
}
// 创建文件映射对象
hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (NULL == hFileMap)
{
TRACE("创建文件映射对象失败,错误代码:%d\r\n", GetLastError());
break;
}
// 偏移地址
__int64 qwFileOffset = 0;
// 块大小
DWORD dwBlockBytes = 1000 * dwGran;
while (qwFileSize > 0)
{
if (qwFileSize < 1000 * dwGran)
{
dwBlockBytes = (DWORD)qwFileSize;
}
// 映射视图
LPBYTE lpbMapAddress = (LPBYTE)MapViewOfFile(hFileMap,FILE_MAP_ALL_ACCESS,
(DWORD)(qwFileOffset >> 32),
(DWORD)(qwFileOffset & 0xFFFFFFFF),
dwBlockBytes);
if (NULL == lpbMapAddress)
{
TRACE("映射文件映射失败,错误代码:%drn", GetLastError());
break;
}
// 对映射的视图进行访问
for(DWORD i = 0; i < dwBlockBytes; i++)
{
BYTE lpbytetemp = *(lpbMapAddress + i);
}
// 撤消文件映像
UnmapViewOfFile(lpbMapAddress);
// 修正参数
qwFileOffset += dwBlockBytes;
qwFileSize -= dwBlockBytes;
}
if(qwFileSize <= 0)
{
bRet = true;
}
} while (false);
if(NULL != hFileMap)
{
// 关闭文件映射对象句柄
CloseHandle(hFileMap);
hFileMap = NULL;
}
if(INVALID_HANDLE_VALUE != hFile)
{
// 关闭文件对象
CloseHandle(hFile);
hFile = INVALID_HANDLE_VALUE;
}
return bRet;
}
内存映射文件处理大文件
最新推荐文章于 2023-07-15 18:52:26 发布