最經開發的時候要用到檔案系統的一些函數,其中一個就是如何删除一個目錄下的所有檔案.
下面試代碼,BOOL bRemoveDir 代表是否移除根目錄,也就是傳進去的目錄,如果傳進去的目錄是移動磁盤的根目錄,那麼移除會失敗,要設定為FASLE.
删除檔案以及目錄除了可以調用系統的快速格式化删除所有檔案,
我這種就是遞歸的找到每個檔案,然後删除檔案,移除目錄。
BOOL DeleteDirectory(CString DirName,BOOL bRemoveRootDir)
{
CFileFind tempFind;
CString csZRootDir;
csZRootDir.Format("%s\\*.*",DirName.GetBuffer(0));
BOOL IsFinded=(BOOL)tempFind.FindFile(csZRootDir.GetBuffer(0));
while(IsFinded)
{
IsFinded=(BOOL)tempFind.FindNextFile();
if(!tempFind.IsDots())
{
CString csFileName;
csFileName.Format("%s",tempFind.GetFileName().GetBuffer(0));
if(tempFind.IsDirectory())
{
CString tmp;
tmp.Format("%s\\%s",DirName.GetBuffer(0),csFileName.GetBuffer(0));
DeleteDirectory(tmp,TRUE);
}
else
{
CString tmp;
tmp.Format("%s\\%s",DirName,csFileName.GetBuffer(0));
DeleteFile(tmp.GetBuffer(0));
}
}
}
tempFind.Close();
if (bRemoveRootDir)
{
if(!RemoveDirectory(DirName))
{
LogRecord(TRUE,_T("remove directory failed! %s \r\n"),DirName);
return FALSE;
}
}
return TRUE;
}