2

I am at a loss as to how dirent entries are ordered. For example, if I had the code

DIR* dir = opendir("/some/directory");
struct dirent* entry;

while ((entry = readdir(dir))
    printf("%s\n", entry->d_name);

This may output something like the following:

abcdef
example3
..
.
123456789
example2
example1

As you can see, this output is not alphabetically ordered. So, I was wondering how exactly dirent entries are ordered? What causes some entries to have a higher precedence than others?

Jongware
  • 22,200
  • 8
  • 54
  • 100
Levi
  • 1,921
  • 1
  • 14
  • 18

2 Answers2

3

They are not ordered alphabetically; they are retrieved in the order that the filesystem maintains them.

The directory "file" simply contains a list of filenames and inode numbers. For some filesystem types, the filesystem prefers to not split a filename/inode value across blocks. As the filesystem adds or removes files from the list, it may find space in one of the blocks. Other schemes (such as frequently-used filenames being earlier in the list) are possible.

A list sorted by filename depends upon the way things are sorted: it can be locale-dependent. (The filesystem does not know or care about your locale-settings). So that decision is left to applications rather than the filesystem itself.

For additional comments, see

Community
  • 1
  • 1
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
2

They are not ordered in any relevant way. It's up to the implementation to retrieve and return directory entries in whatever order is most convenient.

Advanced Programming in the UNIX Environment, 3rd ed., goes a little further and even says that the order is usually not alphabetical (Chapter 4, Section 4.22):

Note that the ordering of entries within the directory is implementation dependent and is usually not alphabetical.

If you're wondering, the output of ls is sorted because ls sorts it.

Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
  • 1
    Whether or not the ordering is "usually" alphabetical depends on the filesystem. Some filesystems store filenames in sorted order, causing the files to always be returned sorted. – Gabe May 28 '15 at 20:58