Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove directory recursively?

Tags:

c++

windows

RemoveDirectory(); Removes only empty directory, but how to remove directories that have files inside?

like image 544
NullPoiиteя Avatar asked Mar 23 '12 10:03

NullPoiиteя


4 Answers

The best solution, if you can use it, is boost::filesystem::remove_all. That way, you don't have to worry about the platform specific stuff. I'm not aware of any other platform independent solution; the usual way otherwise would involve reading the directory, and recursively descending it (but the way to read the directory also uses boost::filesystem or system dependent code).

like image 198
James Kanze Avatar answered Oct 24 '22 01:10

James Kanze


If you are prepared to use the Windows API then the easiest way to get this done is to call SHFileOperation. Use the FO_DELETE operation and don't forget to double null-terminate your directory name.

like image 24
David Heffernan Avatar answered Oct 24 '22 01:10

David Heffernan


Typically, if no library method is available, this is done by recursion. A function iterates all directory entries, deleting 'ordinary' files and calling itself with any directory path found. This destroys whole directory trees, (my Windows version has explicit checks on the path passed to prevent it destroying OS folders in case of accidentally passing in a suicidal parameter).

like image 34
Martin James Avatar answered Oct 23 '22 23:10

Martin James


This may be lame, but consider using

system("rd /s /q ...");

It's ugly, but it's too simple to ignore. It also has all the "how to deal with files on network shares" stuff worked out. Whatever solution you come up with is probably an (incomplete and/or incorrect) reimplementation of rd, so calling out to the external process would actually be nice code reuse. ;-)

like image 3
Frerich Raabe Avatar answered Oct 24 '22 01:10

Frerich Raabe