C + + recursive deletion of a directory instance _c language

Source: Internet
Author: User

This article illustrates the implementation of recursive deletion of a directory by C + +. Share to everyone for your reference. The specific methods are as follows:

The use framework of Cfindfile is as follows:

Copy Code code 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 directory, recursively search it

if (finder. Isdirectory ())
{
CString str = finder. GetFilePath ();
TRACE (_t ("%s\n"), (LPCTSTR) str);
Recurse (str);
}
}

Finder. Close ();
}

The recursive deletion code is as follows:

Copy Code code as follows:
Loop Delete a directory
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 directory, recursively search it

if (ff. Isdirectory ())
{
Recursive directory
CString str = ff. GetFilePath ();
TRACE (_t ("%s\n"), (LPCTSTR) str);
Recursivedelete (str);
Delete Directory
:: Setfileattributesa (str, file_attribute_normal);
:: RemoveDirectory (str);
}
Else
{
deleting files
CString str = ff. GetFilePath ();
TRACE (_t ("%s\n"), (LPCTSTR) str);
:: SetFileAttributes (str, file_attribute_normal);
::D eletefile (str);
}
}

Ff. Close ();

}
int main (int argc, char *argv[])
{
Recursivedelete ("c:\\20_128\\");
return 0;
}

I hope this article will help you with the C + + program design.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.