1. 程式人生 > >MFC 遍歷目錄下指定型別的檔案並複製

MFC 遍歷目錄下指定型別的檔案並複製

void Recurse(CString strDir,CString strExt)
{   
//在指定目錄下查詢指定副檔名的檔案
	CFileFind   finder;
	CString   strCurrDir;   
	strCurrDir = strDir + _T("\\*.*");   
	BOOL bWorking = finder.FindFile(strCurrDir);   
	while(bWorking)   
	{   
		bWorking   =   finder.FindNextFile();     
		CString tempFileName = finder.GetFilePath();
		//cout<< (LPCTSTR) temp<<endl;
		if(finder.IsDots())continue;   
		if(finder.IsDirectory())   
		{   
			CString   str   =   finder.GetFilePath();   
			//   cout   <<   (LPCTSTR)   str   <<   endl;
			Recurse(str,strExt);   
		}
		else
		{
			//MessageBox(tempFileName);
			CString strCurrFileExt = tempFileName.Right(tempFileName.GetLength() - tempFileName.ReverseFind(_T('.')));
			//MessageBox(strCurrFileExt);
			CString strCurrFileName = tempFileName.Right(tempFileName.GetLength() - tempFileName.ReverseFind(_T('\\')) - 1);
			//MessageBox(strCurrFileName);
			CString strDstFileName = m_strOutputPath + _T("\\") + strCurrFileName;
			//MessageBox(strDstFileName);
			if(0 == strCurrFileExt.Compare(strExt))
			{
				int nRet = MCopyFile(tempFileName,strDstFileName,this->m_bCoverWrite);
				CString strMsg = strCurrFileName;
				if(0 == nRet)
				{
					m_nCountFindFilsCopySuccess++;
					strMsg += _T(" :Success");
				}
				else if(-1 == nRet)
				{
					CString str;
					str.Format(_T("複製檔案%s時失敗,該檔案已存在!"),tempFileName);
					//MessageBox(str);
					strMsg += _T(" :") + str;
				}
				m_ctrlListFiles.InsertString(m_nCountTotalFilesFinded,strMsg);
				m_ctrlListFiles.SetCurSel(m_nCountTotalFilesFinded);
				m_nCountTotalFilesFinded++;
			}
			//MessageBox(strCurrFileExt);
		}
	}   
	finder.Close();   
}  

int MCopyFile(CString strSrc, CString strDest, BOOL cover)
{
//複製指定檔案到指定目標,是否覆蓋
	if(!cover)
	{
		if(PathFileExists(strDest))return -1;
	}
	CopyFile(strSrc, strDest, cover);
	return 0;
}

使用PathFileExists(CString)函式,需要

#include <shlwapi.h>

#pragma comment(lib,"Shlwapi.lib")


以上兩個函式呼叫方法:

Recurse(m_strInputPath,m_strExt);