Delete multiple files using wildcards in Windows (C++/MFC)



Following code uses SHFileOperation Windows API to delete multiple files using wild card (silently without any confirmation box). It deletes only files. Not folders. Coded in C++/MFC.

 
BOOL DeleteFiles(CString strWildCardSourcePath)
{
 
	SHFILEOPSTRUCT sfo;
	TCHAR *pFromBuf = NULL;
 
	int iRet;
 
	//2 because extra NULL character is required 
	//for pFrom and pTo otherwise SHFileOperation will fail
	pFromBuf = new TCHAR[strWildCardSourcePath.GetLength()+2];
	memset(pFromBuf,0,(strWildCardSourcePath.GetLength()+2)*sizeof(TCHAR));
	memcpy(pFromBuf,strWildCardSourcePath,strWildCardSourcePath.GetLength()*sizeof(TCHAR));
 
	USES_CONVERSION;
 
	sfo.hwnd  = NULL;
	sfo.pFrom = CT2CW(LPCTSTR(pFromBuf));
	sfo.pTo = NULL;
	sfo.fFlags = FOF_NOCONFIRMATION|FOF_SILENT|FOF_FILESONLY;
	sfo.wFunc = FO_DELETE;
 
	iRet = SHFileOperation(&sfo);
 
	if (pFromBuf)
	{
		delete pFromBuf;
		pFromBuf = NULL;
	}
 
	return (iRet == 0) ? TRUE : FALSE;
}


Leave a Reply

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