in reply to Order of files returned by readdir

The entries are probably returned in whatever order the implementor figured would be the fasted order to return them.

Traditionally Unix filesystems store a list files and directories in an unsorted list. Think of it as an array. The fasted way to return the items is to just loop over the array.

A fast way to insert an item into the array is to insert in the next unused slot. Suppose the filesystem does not keep an index that points to the next free slot so the system just loops over the array until it finds a free slot.

A fast way to remove an item is to loop over the array to find the item and then just mark that slot as unused. The system could sort the array when an item is removed but that takes time so it likely just leaves an open slot wherever an item is removed.

There are filesystems (like ReiserFS) that use trees for indexing to give faster searching. In the end the order that items are returned by readdir is not defined to be sorted in any particular way so it's up to the application to sort the items as required.

Replies are listed 'Best First'.
Re^2: Order of files returned by readdir
by Jim_Gillespie (Initiate) on Mar 02, 2006 at 14:49 UTC
    Personally I view this as a feature - at work I deal with directories containing thousands of files, and often I want to just count them or do something else which is order-independent. So rather than use ls, which always sorts its output somehow, I've written a tiny perl script which just returns the list of files as given by readdir().
      man ls ... -f do not sort, enable -aU, disable -lst
        That's a lot more work than perl -e 'print "@{[readdir $ARGV[0]]}\n"' dir :-)