1. 程式人生 > >MFC 檔案分塊複製

MFC 檔案分塊複製

CFile ReadFile;
BOOL bOpen = ReadFile.Open( pInfo->m_szSrcPath , CFile::modeRead );
if(!bOpen)
{
AfxMessageBox(pInfo->m_szSrcPath + _T("  :檔案開啟失敗!"),MB_ICONERROR|MB_OK);
pInfo->m_stTip.SetWindowText("複製【失敗】!");
pInfo->GetDlgItem(IDC_BUTTON_COPY)->EnableWindow(TRUE);
return 1;
}
//得到檔案的大小,用於計算進度
DWORD dwTotalSize = ReadFile.GetLength();
DWORD dwCompleteSize = 0;//已完成的大小
//計算檔案去讀的步長
DWORD dwStep = STEPLEN > dwTotalSize ? dwTotalSize : STEPLEN;
//資料緩衝區
char *pBuf = new char[dwStep+1];
memset(pBuf, 0x00, dwStep+1);
DWORD dwRead = dwStep;
    //建立目標檔案,若目標檔案存在則清空
CFile WriteFile;
bOpen = WriteFile.Open( pInfo->m_szDesPath,CFile::modeCreate | CFile::modeWrite);
if(!bOpen)
{
AfxMessageBox(pInfo->m_szDesPath + _T("  :檔案開啟失敗!"),MB_ICONERROR|MB_OK);
pInfo->m_stTip.SetWindowText("複製【失敗】!");
pInfo->GetDlgItem(IDC_BUTTON_COPY)->EnableWindow(TRUE);
return 2;
}
//檔案的複製:從原始檔去讀取資料,並寫入到目標檔案中
while( (dwRead = ReadFile.Read(pBuf, dwStep)) > 0 )
{//讀取原始檔,一次一塊
//將讀取的資料寫入目標檔案中
WriteFile.Write( pBuf, dwRead );
dwCompleteSize += dwRead;
pInfo->m_nSpeed += dwRead;
//更新進度
while (!pInfo->pUIThread->PostThreadMessage(WM_THREADINFO, 3, (LPARAM) int((dwCompleteSize*1.0 / dwTotalSize) * 100)))
{
Sleep(10);
}
}
//完成
delete pBuf;
//關閉檔案
ReadFile.Close();
WriteFile.Close();