目前碰到一个需求,需要将A文件中从aOffset处复制 lSize 长度的数据到B长文件的bOffset,由于lSize是个很大的值,假如利用常规 读取->写入 循环模式由于频繁进行IO操作势必影响性能,想到可以利用文件内存映射来完成, 代码实现之(考虑到SDK读写文件需要写很长的代码,所以借助MFC中的CFile来实现)
void CopyFileMap(LPCTSTR lpSrc, DWORD offsetSrc, LPCTSTR lpDest, DWORD offsetDest, DWORD size) { CFile f(lpSrc, CFile::modeReadWrite|CFile::shareDenyNone); HANDLE hFile = (HANDLE)(HFILE)f; HANDLE hFileMapping = CreateFileMapping(hFile,NULL,PAGE_READWRITE, 0, 0, NULL); PBYTE pbFile = (PBYTE)MapViewOfFile(hFileMapping, FILE_MAP_ALL_ACCESS, 0, 0, f.GetLength()); f.Close(); CFile f2(lpDest, CFile::modeReadWrite|CFile::shareDenyNone); HANDLE hFile2 = (HANDLE)(HFILE)f2; DWORD dwDestFileSize = offsetDest + size; HANDLE hFileMapping2 = CreateFileMapping(hFile2, NULL, PAGE_READWRITE, 0, (DWORD)(dwDestFileSize&0xFFFFFFFF), NULL); f2.Close(); PBYTE pbFile2 = (PBYTE)MapViewOfFile(hFileMapping2, FILE_MAP_ALL_ACCESS, 0, 0, dwDestFileSize); memcpy(pbFile2 + offsetDest, pbFile + offsetSrc, size); UnmapViewOfFile(pbFile); UnmapViewOfFile(pbFile2); CloseHandle(hFileMapping); CloseHandle(hFileMapping2); }