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?

Santi Agüero
  • 3,143
  • 8
  • 27
  • 39
  • 1
    You can also directly create the directory after the remove_all – RvdK Jan 30 '13 at 17:36
  • I think one way could be to iterate on folder's content and delete each file. – Santi Agüero Jan 30 '13 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... – Santi Agüero Jan 30 '13 at 17:41

1 Answers1

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());
  }
Ahmed-Anas
  • 5,471
  • 9
  • 50
  • 72
J. Calleja
  • 4,855
  • 2
  • 33
  • 54
  • Do you have any guarantee that removing files from the directory won't invalidate the iterator? – Brice M. Dempsey Dec 07 '16 at 08: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](http://stackoverflow.com/a/18388359/218774) 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 Dec 07 '16 at 13:58