RemoveDirectory(); Removes only empty directory, but how to remove directories that have files inside?
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).
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.
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).
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. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With