Maison > Questions et réponses > le corps du texte
问题
使用内存映射文件的方法,从某个超大的数据文件中查找某个指定的字符串:keyword
并将超大文件中包含keyword关键字的所有行的数据都显示在界面上
注:C++字符串指针这块基础不好,希望哪位朋友可以帮我解决下该问题,谢谢了!
代码
HANDLE hFile = CreateFile(m_FilePath, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
TRACE("Error:%drn", GetLastError());
return;
}
HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
if (hFileMap == NULL)
{
TRACE("Error:%drn", GetLastError());
return;
}
// 得到系统分配粒度
SYSTEM_INFO SysInfo;
GetSystemInfo(&SysInfo);
DWORD dwGran = SysInfo.dwAllocationGranularity;//一般是65536(byte)=64KB
DWORD dwFileSizeHigh;
__int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
qwFileSize |= (((__int64)dwFileSizeHigh) << 32);
CloseHandle(hFile);
__int64 qwFileOffset = 0;
DWORD dwBlockBytes = 1000 * dwGran;
if (qwFileSize < 1000 * dwGran)
dwBlockBytes = (DWORD)qwFileSize;
while (qwFileOffset >= 0)
{
LPBYTE lpbMapAddress = (LPBYTE)MapViewOfFile(hFileMap,FILE_MAP_ALL_ACCESS,
(DWORD)(qwFileOffset >> 32), (DWORD)(qwFileOffset & 0xFFFFFFFF),
dwBlockBytes);
if (lpbMapAddress == NULL)
{
TRACE("Error:%drn", GetLastError());
return;
}
//该函数如何书写呢?从lpbMapAddress所指向的内存地址中搜索所有给定的关键字:keyword
//并返回关键字keyword所在那一行的数据
UnmapViewOfFile(lpbMapAddress);
qwFileOffset += dwBlockBytes;
qwFileSize -= dwBlockBytes;
}
CloseHandle(hFileMap);