19

I'm using boost::filesystem::remove_all operation to remove the content of a directory.

It removes correctly the content, but, as state by Boost Filesystem Documentation, it also removes the directory itself.

Is there an easy way to stay with the directory despite that it's empty?

3
  • 1
    You can also directly create the directory after the remove_all
    – RvdK
    Commented Jan 30, 2013 at 17:36
  • I think one way could be to iterate on folder's content and delete each file. Commented Jan 30, 2013 at 17:40
  • RvdK, you're right, that's the solution I'm using right now... I'm just wondering why Boost People didn't include some "flag" to avoid removing the directory on remove_all operation... Commented Jan 30, 2013 at 17:41

1 Answer 1

26

I think the best way is to iterate inside the folder and perform remove_all for each element. Example code:

  namespace fs=boost::filesystem;
  fs::path path_to_remove("C:\\DirectoryToRemove");
  for (fs::directory_iterator end_dir_it, it(path_to_remove); it!=end_dir_it; ++it) {
    fs::remove_all(it->path());
  }
2
  • Do you have any guarantee that removing files from the directory won't invalidate the iterator? Commented Dec 7, 2016 at 8:12
  • 2
    @BriceM.Dempsey The documentation does not state that the iterator is invalidated when the element it references is deleted. I have find this information that indicates that iterating to delete content seems to be an officially supported use case. Notice that any file can be externally deleted at any time, so the it would be very dangerous to invalidate the iterators just for this reason.
    – J. Calleja
    Commented Dec 7, 2016 at 13:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.