63

I'm getting a list of files on a linux-like system using opendir/readdir. It appears that the directory entries are returned in alphabetical order of file name. However, I don't see anything in the man pages about this order being guaranteed.

Can anyone tell me whether or not readdir guarrantees an order?

Dan Fego
  • 13,644
  • 6
  • 48
  • 59
Tom
  • 18,685
  • 15
  • 71
  • 81
  • 1
    As a rule of thumb, odds are if it's not in the documentation, the answer is no. Even if there happened to be a consistent order on all implementations, if it's not documented, it's probably not guaranteed. – Dan Fego Jan 23 '12 at 19:34
  • 4
    If they're coming out alphabetical, that's almost surely just that they were originally *created* in alphabetical order, e.g. by `unzip` or `tar` extracting them as such... `readdir` provides no order. – R.. GitHub STOP HELPING ICE Jan 23 '12 at 19:39
  • 1
    By the way, `scandir` may be useful if you want to order the results or have random access to them. It's standardized in POSIX 2008 and was a common extension before then. – R.. GitHub STOP HELPING ICE Jan 23 '12 at 19:42
  • 1
    The ordering you gets depends almost surely from the filesystem. On FAT32 I get the files in order of creation, on NTFS usually in alphabetical order but with some exceptions, on ext4 in no apparent order. There goes your guaranteed order. :) – Matteo Italia Jan 23 '12 at 19:42
  • I've even seen a case where "." and ".." weren't the first entries (in a network mounted file system). And I wouldn't count much on the order of creation when creations and deletions are intermixed. – AProgrammer Jan 24 '12 at 10:51

7 Answers7

53

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

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.

ZachB
  • 13,051
  • 4
  • 61
  • 89
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
14

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

Alex Shpilkin
  • 776
  • 7
  • 17
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
12

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.

Mingye Wang
  • 1,107
  • 9
  • 32
efannu-723
  • 121
  • 2
9

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.

8

No, readdir does not guarantee any order.

(Some file systems might store directory entries in a certain order, in such cases readdir might return them to you in the same order, but that's not a feature of readdir itself.)

nos
  • 223,662
  • 58
  • 417
  • 506
3

readdir() does not guarantee any other order above that which is OS disk read order.


According to test which i made on few platforms - Solaris - sun4sol, x86 sol, linux, Windows with the sample code all results were displated in a random manner.


source: readdir() beginning with dots instead of files

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

int main() {
    
    DIR *dir;
    struct dirent *dp;
    char * file_name;
    char dirpath [100] ;


    while(1==1){
        printf("Choose dir:");
        scanf("%s",dirpath);
        dir = opendir(dirpath);
        while ((dp=readdir(dir)) != NULL) {
            if ( !strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") )
            {
                // do nothing (straight logic)
            } else {
                file_name = dp->d_name; // use it
                printf("file_name: \"%s\"\n",file_name);
            }
        }
        closedir(dir);
    }

    return 0;
}
Lothar
  • 12,537
  • 6
  • 72
  • 121
Wojciech Papaj
  • 431
  • 4
  • 2
1

In addition to the other answers, the readdir man page is pretty clear about files ordering.

The order in which filenames are read by successive calls to readdir() depends on the filesystem implementation; it is unlikely that the names will be sorted in any fashion.

Some file systems, like ReiserFS do list the files in lexical order.

In your case, you have to store the names in an array, then sort the array.

For instance, use qsort() to sort the array.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100