What the standard(s) say about the order of
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
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
contains a great deal of verbiage about how
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
(I am not up on standards wonkery enough to understand what is implied
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.
Comments on this page:Written on 07 September 2012.