enzom83
enzom83

Reputation: 8320

What determines the order in which the files are listed?

The following code sample allows you to know all the files within a directory.

DIR *pDIR;
struct dirent *entry;

if( (pDIR = opendir(path)) != NULL )
{
    while( (entry = readdir(pDIR)) != NULL )
    {
    if( strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 )
    {
            string path_to_file(path);
            path_to_file.append("/");
            path_to_file.append(entry->d_name);

            cout << path_to_file << endl;
        }
    }
}

The files are not listed in alphabetical order: what determines the order in which they are listed?

Upvotes: 0

Views: 181

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129454

As James has said, there is nothing specifying the order. It is entirely up to the filesystem to order the files in any order it likes. In Windows NTFS (and OS/2's HPFS) files are indeed ordered in alphabetical order (in a form of binary tree, making it easy to search for files by name). In the "DOS" FAT file-system, the files are in the order they were created, and if a file is deleted, that "slot" is used for the next file that is created. In the Linux operating systems ext{2,3,4} is the most commonly used, which I believe it is similar to FAT, but the exact structure isn't the same.

There are dozens of other filesystems (for Linux there are at least half a dozen, and almost every OS that I haven't mentioned by name has its own variation), which all have their own ways of doing things. If you want to reliably have the files sorted in any particular order, you will have to sort them.

Upvotes: 4

James Kanze
James Kanze

Reputation: 153977

Nothing, really. They're listed in the order they are found in the directory. Which is not specified; in practice, it depends on the entire history of what has occurred in the directory.

Upvotes: 1

Related Questions