通过遍历复制文件和目录






2.94/5 (10投票s)
2006年7月6日

33614
通过遍历函数创建目录和复制文件
引言
我在Google上搜索了很多网站,但没有找到使用遍历算法复制文件的代码片段。经过一番努力,我找到了它,并想与大家分享。它很简单,我将代码片段包含在下面。这是我在这里的第一次提交。
代码
这在按钮点击事件中执行
void CCopyFilesFrmFoldersDlg::OnButCopy()
{
CString csSourceDir(_T("")), csDestDir(_T(""));
UpdateData(TRUE);
GetDlgItemText(IDC_EDIT_SOURCE, csSourceDir);
GetDlgItemText(IDC_EDIT_DEST, csDestDir);
CopyDirAndFiles(csSourceDir, csDestDir);
}
这在 CopyDirAndFiles
函数中执行
bool CCopyFilesFrmFoldersDlg::CopyDirAndFiles(CString csSource, CString csDest)
{
bool bReturn = false;
try
{
CFileFind oFileFind;
CString csSourceFilePath(""),csDestFilePath("");
int nSym(0), nTot(0);
CString csTemp("");
csSourceFilePath = csSource;
csSourceFilePath += "\\*.*";
/////////start looping////////
BOOL bWorking = oFileFind.FindFile(csSourceFilePath);
while (bWorking)
{
////////////Search for next file///
bWorking = oFileFind.FindNextFile();
///////////File Path Name//////////
csSourceFilePath = oFileFind.GetFilePath();
if(oFileFind.IsDirectory())
{
if(oFileFind.GetFileName().CompareNoCase(".")==0||
oFileFind.GetFileName().CompareNoCase("..")==0)
continue;
csDestFilePath = csDest;
nSym = csSourceFilePath.ReverseFind('\\');
nTot = csSourceFilePath.GetLength();
csTemp = csSourceFilePath.Right(nTot - nSym);
csDestFilePath += csTemp;
CreateDirectory(csDestFilePath, NULL);
CopyDirAndFiles(csSourceFilePath, csDestFilePath);
}
else
{
csDestFilePath = csDest;
nSym = csSourceFilePath.ReverseFind('\\');
nTot = csSourceFilePath.GetLength();
csTemp = csSourceFilePath.Right(nTot - nSym);
csDestFilePath += csTemp;
CopyFile(csSourceFilePath, csDestFilePath, FALSE);
}
}
oFileFind.Close();
bReturn = true;
}
catch(...)
{
bReturn = false;
}
return bReturn;
}
希望对您有所帮助...
历史
- 2006年7月6日:初始发布