Copy or move files using wildcards to another folder in Windows (C++/MFC)



The following function uses SHFileOperation Windows API to copy multiple files using wildcards to another folder. It has option to delete files from source location too (Whether to copy or to move the files. It copies silently without any confirmation message box. It copies only files. Not the folders.

 
BOOL CopyFiles(CString strWildCardSourcePath, CString strTargetPath, BOOL bDeleteFilesFromSourceLocation
								, FILEOP_FLAGS fFlags /*= FOF_NOCONFIRMATION|FOF_SILENT|FOF_FILESONLY*/)
{
 
	SHFILEOPSTRUCT sfo;
	TCHAR *pFromBuf = NULL, *pToBuf = NULL;
 
	int iRet;
 
	//2 for ending NULL characters required by SHFileOperation function's pFrom and pTo
	pFromBuf = new TCHAR[strWildCardSourcePath.GetLength()+2];
	memset(pFromBuf,0,(strWildCardSourcePath.GetLength()+2)*sizeof(TCHAR));
	memcpy(pFromBuf,strWildCardSourcePath,strWildCardSourcePath.GetLength()*sizeof(TCHAR));
 
	//2 for ending NULL characters required by SHFileOperation function's pFrom and pTo
	pToBuf = new TCHAR[strTargetPath.GetLength()+2];
	memset(pToBuf,0,(strTargetPath.GetLength()+2)*sizeof(TCHAR));
	memcpy(pToBuf,strTargetPath,strTargetPath.GetLength()*sizeof(TCHAR));
 
	USES_CONVERSION;
 
	sfo.hwnd  = NULL;
	sfo.pFrom = CT2CW(LPCTSTR(pFromBuf));
	sfo.pTo = CT2CW(LPCTSTR(pToBuf));
	sfo.fFlags = fFlags;
	sfo.wFunc = (bDeleteFilesFromSourceLocation) ? FO_MOVE : FO_COPY ;
 
	iRet = SHFileOperation(&sfo);
 
	if (pFromBuf)
	{
		delete pFromBuf;
		pFromBuf = NULL;
	}
 
	if (pToBuf)
	{
		delete pToBuf;
		pToBuf = NULL;
	}
 
	return (iRet == 0) ? TRUE : FALSE;
 
}


Leave a Reply

Your email address will not be published. Required fields are marked *