On 09/07/16 16:06, Andrzej Krzemienski wrote:
Hi, I wonder what is boost::filesystem recommendation for solving the following problem.
I want to remove all files from a given directory that satisfy a certain predicate, e.g., only these whose names start with letter "s".
It is my understanding that the calling filesystem::remove may invalidate the iterator, and therefore the following solution is incorrect:
fsys::directory_iterator it{path}, itEnd{}; for ( ; it != itEnd ; ++it ) { if (predicate(*it)) fsys::remove(it->path()); }
But, is the following guaranteed to work?:
fsys::directory_iterator it{path}, itEnd{}; for ( ; it != itEnd ; ) { if (predicate(*it)) fsys::remove((it++)->path()); else ++it; }
From the documentation, it seems the behavior should be similar to readdir, in which case it would seem that both pieces of code above are valid. Although I would prefer the second one as it is more in line with common practices in C++.
If not, does there exist a dedicated solution for solving this problem that would not require of me N traversals through the directory?
If you still want a different solution, you could collect the matching file names on the directory traversal and delete the files in the second loop.