内存映射的小例子

bool CopyThread::copyFileDW(const QString& orgPath, QString tarPath) { // source file HANDLE hIn = CreateFile(orgPath.toStdWString().c_str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if ( INVALID_HANDLE_VALUE == hIn ) { return false; } HANDLE hInMapFile = CreateFileMapping(hIn, NULL, PAGE_READWRITE, 0, 0, NULL); if ( INVALID_HANDLE_VALUE == hInMapFile ) { CloseHandle(hIn); return false; } DWORD dwInFileSizeHigh = 0; __int64 qwInFileSize = GetFileSize(hIn, &dwInFileSizeHigh); qwInFileSize |= (((__int64)dwInFileSizeHigh) << 32); CloseHandle(hIn); // dest file HANDLE hOut = CreateFile(tarPath.toStdWString().c_str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if ( INVALID_HANDLE_VALUE == hOut ) { CloseHandle(hInMapFile); return false; } HANDLE hOutMapFile = CreateFileMapping(hOut, NULL, PAGE_READWRITE, (DWORD)(qwInFileSize>>32),(DWORD)(qwInFileSize & 0xFFFFFFFF), NULL); if ( INVALID_HANDLE_VALUE == hOutMapFile ) { CloseHandle(hInMapFile); CloseHandle(hOut); return false; } DWORD dwOutFileSizeHigh = 0; __int64 qwOutFileSize = GetFileSize(hOut, &dwOutFileSizeHigh); qwOutFileSize |= (((__int64)dwOutFileSizeHigh) << 32); CloseHandle(hOut); __int64 qwFileOffset = 0; SYSTEM_INFO sinf; GetSystemInfo(&sinf); DWORD dwBlock = 1000*sinf.dwAllocationGranularity; float fPercent = 0.0f; LPBYTE pInMapAddress = NULL; LPBYTE pOutMapAddress = NULL; while(qwInFileSize > 0) { if(!m_bCopying) { CloseHandle(hInMapFile); CloseHandle(hOutMapFile); return false; } if(qwInFileSize < dwBlock) dwBlock = (DWORD)qwInFileSize; pInMapAddress = (LPBYTE)MapViewOfFile(hInMapFile, FILE_MAP_READ, (DWORD)(qwFileOffset>>32),(DWORD)(qwFileOffset & 0xFFFFFFFF), dwBlock); if(NULL == pInMapAddress) break; pOutMapAddress = (LPBYTE)MapViewOfFile(hOutMapFile, FILE_MAP_WRITE, (DWORD)(qwFileOffset>>32),(DWORD)(qwFileOffset & 0xFFFFFFFF), dwBlock); if(NULL == pOutMapAddress) break; CopyMemory(pOutMapAddress, pInMapAddress, dwBlock); UnmapViewOfFile(pInMapAddress); UnmapViewOfFile(pOutMapAddress); qwFileOffset += dwBlock; qwInFileSize -= dwBlock; mcopysize += dwBlock; fPercent = (float)mcopysize/mFileSize; fPercent = qBound(0.0f, fPercent, 1.0f); // 向主线程汇报 emit sig_updateProgress(fPercent); } if(NULL != pInMapAddress) UnmapViewOfFile(pInMapAddress); if(NULL != pOutMapAddress) UnmapViewOfFile(pOutMapAddress); CloseHandle(hInMapFile); CloseHandle(hOutMapFile); return true; }

你可能感兴趣的:(内存映射的小例子)