MTLaurentys
MTLaurentys

Reputation: 221

Does boost directory_iterator visit files and folders in alphabetical order on Windows

I have a folder fold with subfolders sub1, sub2... subX, with unique files inside.

Let's say I need to find the first occurrence of file X.

All I need is to get a fold iterator that goes though subX in order or get a list of folders and order it myself. I ran it a couple of times and I noticed that the iterator is indeed going in alphabetical order, however, I could not find it specified on the documentation, so it might be a coincidence. I see however:

The Linux listing isn't sorted. That's because the ordering of directory iteration is unspecified. Ordering depends on the underlying operating system API and file system specifics. So we need to sort the results ourselves.

EDIT: Files in fold are always generated in alphabetical order, in case that changes anything...

Question:

Can I trust that it is always going to iterate in order? Does Windows' "underlying operating system API" specify order? Based on this article: What order does the DIR command arrange files if no sort order is specified, I would not think so.

Upvotes: 3

Views: 2111

Answers (2)

Alan Birtles
Alan Birtles

Reputation: 36419

boost::filesystem will be implemented in terms of FindFirstFile and FindNextFile on windows.

The documentation of these functions states:

The order in which the search returns the files, such as alphabetical order, is not guaranteed, and is dependent on the file system. If the data must be sorted, the application must do the ordering after obtaining all the results.

Upvotes: 5

eerorika
eerorika

Reputation: 238391

Can I trust that it is always going to iterate on order?

The reference says:

The order of directory entries obtained by dereferencing successive increments of a directory_iterator is unspecified.

Therefore no, you can never trust that it is ever going to iterate in order.

If you need a specific order, then you can store the entries into a container, sort it, and then iterate the container.


PS. Same applies to std::filesystem::directory_iterator as well.

Upvotes: 4

Related Questions