In what order does readdir() see a directory?

C

Charles Packer

In what order does readdir() see the
entries in a directory (in a Unix
environment)? I'm posting about this
as a sort of public service -- a search
shows that nobody's posted herein about
this gotcha.

Tests on several directories seemed to
indicate that "." and ".." always come
first. The examples in "Perl Cookbook"
and other places include a check for these
inside the loop...but hey, if I'm processing
directories with thousands of files, as in

while (defined($FileName = readdir(DIR))) {

seems not unreasonably anal to eliminate
those two pesky entries right away with two
premptive readdir() calls before entering
the loop, right? Bad idea!
 
P

Peter Makholm

Charles Packer said:
In what order does readdir() see the
entries in a directory (in a Unix
environment)?

The order of entries returned by readdir is not defined. It depends on
the filesystem, filesystem settings and for some filesystems the order
which the files is added and removed from the directory and for other
filestsyems is is purly based on their names.

Many (older) filesystems just allocated directory entries in some
blocks on the filesystem and scans these blocks lineary when doing a
readdir. Then '.' and '..' will always be the first. Ext3 on Linux
usually uses hashed b-trees to store directory entries. On these
systems the order is purly based on the name of the files in the
directory, but seemingly random due to hashing.

directories with thousands of files, as in

while (defined($FileName = readdir(DIR))) {

seems not unreasonably anal to eliminate
those two pesky entries right away with two
premptive readdir() calls before entering
the loop, right? Bad idea!

That wouldn't work in a portable way.

//Makholm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top