This example enables a TXT file under a folder to be copied to the destination folder. The method is to traverse the source folder and, if it is a TXT file, copy it.
int Ctestcsdndlg::copyfileex (CString strsrcpath, CString strext, CString Strdespath)
{
CFileFind FF;
CString szdir = Strsrcpath;
CString strsize = _t ("");
if (Szdir.right (1)! = "//")
Szdir + = "//";
Szdir + = "* *";
BOOL res = ff. FindFile (Szdir);
while (RES)
{
res = ff. FindNextFile ();
if (ff. Isdirectory () &&!ff. Isdots ())//Folder
{
CString Strfolderpath = ff. GetFilePath ();
CopyFileEx (Strfolderpath, Strext, Strdespath);
}
else if (!ff. Isdirectory () &&!ff. Isdots ())//File
{
To determine the extension name
CString strFileName = ff. GetFileName ();
int NPos;
NPos = Strfilename.reversefind (_t ('. '));
CString Strfileext;
Strfileext = Strfilename.right (Strfilename.getlength ()-nPos-1);
if (Strfileext = = Strext)
{
Copying files
CString strFilePath;
strFilePath = ff. GetFilePath ();
CString Strnewfilepath;
Strnewfilepath = Strdespath + _t ("//") + strFileName;
:: CopyFile (strFilePath, Strnewfilepath, FALSE);
}
}
}
Ff. Close ();
return 0;
}
How to use:
CopyFileEx (_t ("E://test"), _t ("txt"), _t ("E://test 2"));
First parameter: source path
Second parameter: extension
Third parameter: Destination path
If the copy includes subfolders, use the following method:
Modify this snippet:
if (ff. Isdirectory () &&!ff. Isdots ())//Folder
{
CString Strfolderpath = ff. GetFilePath ();
CString strfoldername = ff. GetFileName ();
CString Strdestsubfolder = Strdespath + _t ("//") + strFolderName;
CreateDirectory (Strdestsubfolder, NULL);
CopyFileEx (Strfolderpath, Strext, Strdestsubfolder);
}