Boost logo

Boost :

Subject: Re: [boost] [filesystem] How to remove specific files from a directory?
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2016-09-07 10:45:29


On 09/07/16 17:07, Mateusz Loskot wrote:
> On 7 September 2016 at 15:46, Andrey Semashev <andrey.semashev_at_[hidden]> wrote:
>> 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.
>
> Indeed, boost::filesystem and std::filesystem (ISO/IEC TS 18822:2015) as well
> as POSIX readdir behave in the same way.
> But, for all of them, behaviour is unspecified in case content of
> directory that is
> being traversed changes.

It is unspecified whether the removed/added files will be discovered as
part of the traversal. Other than that the behavior is defined. For
instance, the implementation should not crash and the iterator should
still reach the end at some point.


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