本文實例講述了C++遞歸刪除一個目錄的實現方法。分享給大家供大家參考。具體方法如下:
CFindFile的使用框架如下:
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("http://*.*");
// start working for files
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking)
{
bWorking = finder.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (finder.IsDots())
continue;
// if it's a directory, recursively search it
if (finder.IsDirectory())
{
CString str = finder.GetFilePath();
TRACE(_T("%s/n"), (LPCTSTR)str);
Recurse(str);
}
}
finder.Close();
}
遞歸刪除代碼如下:
//循環刪除一個目錄
void RecursiveDelete(CString strDir)
{
CFileFind ff;
CString strPath;
strPath = strDir;
if (strPath.Right(1) != '//')
{
strPath += '//';
}
strPath += "*.*";
BOOL bWorking = ff.FindFile(strPath);
while (bWorking)
{
bWorking = ff.FindNextFile();
// skip . and .. files; otherwise, we'd
// recur infinitely!
if (ff.IsDots())
continue;
// if it's a directory, recursively search it
if (ff.IsDirectory())
{
//遞歸目錄
CString str = ff.GetFilePath();
TRACE(_T("%s/n"), (LPCTSTR)str);
RecursiveDelete(str);
//刪除目錄
::SetFileAttributesA(str, FILE_ATTRIBUTE_NORMAL);
::RemoveDirectory(str);
}
else
{
//刪除文件
CString str = ff.GetFilePath();
TRACE(_T("%s/n"), (LPCTSTR)str);
::SetFileAttributes(str, FILE_ATTRIBUTE_NORMAL);
::DeleteFile(str);
}
}
ff.Close();
}
int main(int argc, char *argv[])
{
RecursiveDelete("C://20_128//");
return 0;
}
希望本文所述對大家的C++程序設計有所幫助。