C++ recursively deletes a directory instance
- 2020-04-02 02:52:15
- OfStack
This article illustrates the implementation of C++ recursively deleting a directory. Share with you for your reference. Specific methods are as follows:
The usage framework of CFindFile is as follows:
void Recurse(LPCTSTR pstr)
{
CFileFind finder;
// build a string with wildcards
CString strWildcard(pstr);
strWildcard += _T("\*.*");
// 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("%sn"), (LPCTSTR)str);
Recurse(str);
}
}
finder.Close();
}
The recursive delete code is as follows:
//Loop deletes a directory & NBSP; < br / >
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())
{
//Recursive directory & NBSP; < br / >
CString str = ff.GetFilePath();
TRACE(_T("%sn"), (LPCTSTR)str);
RecursiveDelete(str);
//Delete the directory & NBSP; < br / >
::SetFileAttributesA(str, FILE_ATTRIBUTE_NORMAL);
::RemoveDirectory(str);
}
else
{
//Delete the file & NBSP; < br / >
CString str = ff.GetFilePath();
TRACE(_T("%sn"), (LPCTSTR)str);
::SetFileAttributes(str, FILE_ATTRIBUTE_NORMAL);
::DeleteFile(str);
}
}
ff.Close();
}
int main(int argc, char *argv[])
{
RecursiveDelete("C:\20_128\");
return 0;
}
Hope that the article described in the C++ programming to help you.