Is boost :: filesystem :: directory_iterator an invalid delete path?

I repeat through the directory, and when an item meets some criteria, I delete it. Can I do this safely from a loop or do I need to save the paths in an array and delete then?

I did not find the relevant information in boost :: filesystem docs .

+2
source share
2 answers

Quote from the first part of the note attached to the docs boost :: filesystem :: directory_iterator (emphasis mine):

Programs that iterate over directories might want to check if the path obtained by dereferencing the directory iterator really exists. This may be a symbolic link to a nonexistent file. Recursively moving directory trees for the purpose of deleting and renaming entries might want to avoid the following symbolic links.

It becomes clear to me that iterating a directory to delete files is an officially supported use case and therefore will not invalidate the iterator. Also, quoting the second part of this note:

If a file is deleted from the directory or added to the directory after creating an identifier directory for the directory, it is not indicated whether the subsequent increment of the iterator will ever result in an iterator whose value is a deleted or added directory entry. See ISO / IEC 9945 readdir_r () .

This is a very specific statement about whether a deleted file will appear during iteration over the directory. Again, I understand that the iteration process itself remains valid.

Please note that ISO / IEC 9945 has a similar wording.

+6
source

On Windows, this is true, but I found Ubuntu on which the iterator becomes invalid after uninstall, so the next access throws an exception.

So, I used something like this:

recursive_directory_iterator end; for (recursive_directory_iterator itr(folderPath); itr != end; ) { path filePath = *itr++; if (is_regular_file(filePath) && filePath.string().find(filter) != std::string::npos) { if (remove(filePath)) { removedFilesCounter++; } } } 
+1
source

All Articles