Introduction
I have searched many sites in Google but was not lucky enough to find a code snippet which is used for copying files using traverse algorithm. I got it after a little effort and I want to share it with friends out there. It is simple and I am including the code snippet below. This is my first submission here.
The Code
This comes under the button click:
void CCopyFilesFrmFoldersDlg::OnButCopy()
{
CString csSourceDir(_T("")), csDestDir(_T(""));
UpdateData(TRUE);
GetDlgItemText(IDC_EDIT_SOURCE, csSourceDir);
GetDlgItemText(IDC_EDIT_DEST, csDestDir);
CopyDirAndFiles(csSourceDir, csDestDir);
}
This goes in the function 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 += "\\*.*";
BOOL bWorking = oFileFind.FindFile(csSourceFilePath);
while (bWorking)
{
bWorking = oFileFind.FindNextFile();
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;
}
Hope it helps...
History
- 6th July, 2006: Initial post