Does readdir() guarantee an order?

The readdir method doesn't guarantee any ordering. If you want to ensure they are sorted alphabetically you'll need to do so yourself.

Note: I searched for a bit for definitive documentation saying this is the case. The closest I came is the following link

  • http://utcc.utoronto.ca/~cks/space/blog/unix/ReaddirOrder

It's by no means definitive but it does give a nice overview of the command, its history and how its implementation is typically traversal order.


In short, no, readdir() does not guarantee any particular order.

from a readdir example in the glibc manual

The order in which files appear in a directory tends to be fairly random. A more useful program would sort the entries (perhaps by alphabetizing them) before printing them


From "The linux programming interface":

The filenames returned by readdir() are not in sorted order, but rather in the order in which they happen to occur in the directory (this depends on the order in which the file system adds files to the directory and how it fills gaps in the directory list after files are removed). (The command ls –f lists files in the same unsorted order that they would be retrieved by readdir().)

We can use the function scandir(3) to retrieve a sorted list of files matching programmer-defined criteria; see the manual page for details. Although not specified in SUSv3, scandir() is provided on most UNIX implementations.

Note: scandir is a part of POSIX.1-2008. A permissibly-copyrighted version defined around readdir is available in FreeBSD libc.


It's explicitly not guaranteed. The ordering often follows some rules, but the rules are complicated enough that you should not rely on them. The ordering may, for example, be affected by other operations happening in the same directory, and you can't control those. Treat the ordering as random, and sort things yourself if you need to.