Deleting a Directory including all files and sub directories

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
ashish
Earned a small fee
Earned a small fee
Posts: 14
Joined: Thu May 26, 2005 4:15 pm

Deleting a Directory including all files and sub directories

Post by ashish »

Code: Select all

bool CMyClass::DeleteDirectory(wxString filename)
{
	bool dir_empty = false;
	{
		wxDir dir(filename);
		if ( !dir.IsOpened() )
		{
			// deal with the error here - wxDir would already log an error message
			// explaining the exact reason of the failure
			return FALSE;
		}
		wxString file;
		
		bool cont = dir.GetFirst(&file);
		file = filename + wxFileName::GetPathSeparator()+ file;
		while ( cont )
		{
			if(wxFileName::FileExists(file)) wxRemoveFile(file);
			if( wxFileName::DirExists(file)) DeleteDirectory(file);
			cont = dir.GetNext(&file);
			file = filename + wxFileName::GetPathSeparator()+ file;
		}
		if(!(dir.HasFiles() || dir.HasSubDirs()))dir_empty = true;
	}
	if(dir_empty){
		bool error = wxRmdir(filename);
		return TRUE;
	}
	return FALSE;
}
ssigala
Earned some good credits
Earned some good credits
Posts: 109
Joined: Fri Sep 03, 2004 9:30 am
Location: Brescia, Italy

Post by ssigala »

Good work ashish! :)

P.S. maybe the while loop can be reworked a bit like this:

Code: Select all

                wxString file;
                bool cont = dir.GetFirst(&file);
                while ( cont )
                {
                        file = filename + wxFileName::GetPathSeparator()+ file;
                        if(wxFileName::FileExists(file)) wxRemoveFile(file);
                        if( wxFileName::DirExists(file)) DeleteDirectory(file);
                        cont = dir.GetNext(&file);
                }
Sandro Sigala - Kynosoft, Brescia
vdell
Ultimate wxWidgets Guru
Ultimate wxWidgets Guru
Posts: 536
Joined: Fri Jan 07, 2005 3:44 pm
Location: Finland
Contact:

Post by vdell »

There is also another version @ http://forums.wxwidgets.org/viewtopic.php?t=2519
Visual C++ 9.0 / Windows XP Pro SP3 / wxWidgets 2.9.0 (SVN) | Colligere
Jorg
Moderator
Moderator
Posts: 3971
Joined: Fri Aug 27, 2004 9:38 pm
Location: Delft, Netherlands
Contact:

Post by Jorg »

Minor suggestion, use the wxFileName::AppendDir function instead of dealing with the path seperator. The AppendDir will deal with it for you. By using a wxFileName to begin with (instead of wxString) you do not have to concatenate all the time ;-)

But besides that it's another useful contribution to the Code Dump, thanks!
- Jorgen
Forensic Software Engineer
Netherlands Forensic Insitute
http://english.forensischinstituut.nl/
-------------------------------------
Jorg's WasteBucket
http://www.xs4all.nl/~jorgb/wb
Post Reply