If somebody creates or deletes a file in a directory while I am enumerating its contents, what happens?

Raymond Chen

Raymond

Suppose you are enumerating the contents of a directory via Find­First­File and Find­Next­File, and while your loop is running, somebody creates or deletes a file in that directory. What can be said about the result of the enumeration?

Are you guaranteed that the effect of the creation or deletion will not be visible in the enumeration? In other words, will the enumeration show the contents of the directory at the time the enumeration started, even if the directory contents change later? Or maybe the guarantee is the opposite: Are you guaranteed that the deleted file will be removed from the enumeration and the created file will be added to it?

Actually, there is no guarantee either way.

What you can say is that files which were neither created nor deleted during the enumeration will be enumerated. If a file is created during the enumeration, it is unspecified whether it will appear in the enumeration. Similarly, if a file is deleted during the enumeration, it is unspecified whether it will be removed from the enumeration. (And if a file is deleted, then recreated, it may show up more than once!)

We noted some time ago that the Find­First­File function does some batching, and the Find­First­File­Ex function lets you influence the size of the batches. If a file is deleted while it is sitting in a batch, then the Find­Next­File function will return it, because it is just handing data out from the most recent batch. And if an error occurs during the enumeration, you should just give up, because there’s no meaningful recovery.

Raymond Chen
Raymond Chen

Follow Raymond