C++切割文件

时间:2024-11-18 11:35:32
void CFileCutter::DoSplit()
{
int nCompleted = ; //计数
CString strSourceFile = m_strSource; //取得全局变量赋值给局部变量,方便操作
CString strDestDir = m_strDest;
CFile sourceFile, destFile;
//打开文件
BOOL bOK = sourceFile.Open(strSourceFile, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary);
if (!bOK)//打不开就报错退出
{
::PostMessage(m_hWndNotify, WM_CUTTERSTOP, exitSourceErr, nCompleted);
return;
}
int nPos = ;
//逐层创建文件夹(不存在就创建)
while ((nPos = strDestDir.Find('\\', nPos + )) != -)//少了个括号
{
::CreateDirectory(strDestDir.Left(nPos),NULL);
}
::CreateDirectory(strDestDir, NULL); //创建最底层文件夹
if (strDestDir.Right() != '\\')
{
strDestDir += '\\';
}
int nTotalFiles = sourceFile.GetLength() / m_uFileSize + ;//判断切割后文件数
::PostMessage(m_hWndNotify,WM_CUTTERSTART,nTotalFiles,TRUE); //设置进度条长度
const int c_page = * ; //每次读取大小
char buff[c_page]; //缓冲区
DWORD dwRead; CString sDestName;
int nPreCount = ;
UINT uWriteBytes; do
{
//设置文件名并创建文件
sDestName.Format(TEXT("%d_"), nPreCount);
sDestName += sourceFile.GetFileName();
if (!destFile.Open(strDestDir + sDestName, CFile::modeWrite | CFile::modeCreate))
{
PostMessage(m_hWndNotify, WM_CUTTERSTOP, exitDestErr, nCompleted);
sourceFile.Close();
return;
}
uWriteBytes = ;
do
{
//读写操作
if (!m_bContinue) //stopCutter函数
{
destFile.Close();
sourceFile.Close();
if (!m_bExitThread) //析构函数
{
::PostMessage(m_hWndNotify, WM_CUTTERSTOP, exitUserForce, nCompleted);
}
return;
}
dwRead = sourceFile.Read(buff, c_page);//读
destFile.Write(buff, dwRead); //写
uWriteBytes += dwRead; //计数 } while (dwRead > && uWriteBytes < m_uFileSize);//读出了数据并且一共写的数据量小于用户要求的数据量
destFile.Close(); //当前文件写完了,关闭
nCompleted = nPreCount++; //计数
::PostMessage(m_hWndNotify, WM_CUTTERSTATUS, , nCompleted); } while (dwRead > ); //只要读出了数据就循环继续,直到源文件全部读出。
sourceFile.Close(); //最后关闭原文件
::PostMessage(m_hWndNotify, WM_CUTTERSTOP, exitSuccess, nCompleted);
}