Boost logo

Boost :

Subject: [boost] [filesystem] How to remove specific files from a directory?
From: Andrzej Krzemienski (akrzemi1_at_[hidden])
Date: 2016-09-07 09:06:49


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;
}

If not, does there exist a dedicated solution for solving this problem that
would not require of me N traversals through the directory?

Thanks,
&rzej;


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk