What the standard(s) say about the order of readdir()'s results

September 7, 2012

A while back I wrote about the pragmatic answer to what order readdir() returns results in. Inspired by a high-scoring Stackoverflow answer to a question about readdir()'s order, today's topic is what the standards have to say about this. Or at least the readily accessible Single Unix Standard, since you can find that online.

Reading Unix standards, like reading any standard, requires just as careful attention to what they don't say as to what they do say. The SuS page on readdir() contains a great deal of verbiage about how readdir() behaves, and it does say that readdir() returns an ordered sequence of all of the directory entries. However, it does not say anything about what that order is. The conclusion is straightforward; since the standard doesn't specify an ordering, it doesn't require any particular one. A standards-conformant system is allowed to return directory entries in whatever order it likes and a standards-conformant program can't assume that directory entries are in any particular order.

(I am not up on standards wonkery enough to understand what is implied by requiring readdir() to return an ordered sequence. Besides, this may be seeing too much meaning in the wording of the SuS. Reading standards is an exercise on alternately caring about the most tiny speck and passing blithely over various large things, which is one reason I don't like to do it very often.)

As it happens, this is also the pragmatic answer. Existing Unix versions and existing (different) filesystems on single Unix versions return filenames in different, unpredictable, and essentially random orders. Any program that wants to use readdir() needs to deal with this, unless it is running in very unusual circumstances.

Written on 07 September 2012.
« A little trick and gotcha with Exim ratelimits
When you can log bad usernames for failed authentications »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri Sep 7 01:51:11 2012
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.