In what order does readdir() see a directory?

Discussion in 'Perl Misc' started by Charles Packer, Aug 10, 2007.

  1. 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!

    --
    Charles Packer
    http://cpacker.org/whatnews
    mailboxATcpacker.org
    Charles Packer, Aug 10, 2007
    #1
    1. Advertising

  2. Charles Packer <> writes:

    > 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
    Peter Makholm, Aug 10, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt
    Replies:
    2
    Views:
    734
  2. Ramon
    Replies:
    5
    Views:
    10,785
    John C. Bollinger
    Jan 3, 2005
  3. electric sheep

    readdir() and S_ISDIR(stat.st_mode) question (OT ?)

    electric sheep, Mar 4, 2004, in forum: C Programming
    Replies:
    2
    Views:
    11,511
    Villy Kruse
    Mar 4, 2004
  4. John Stoffel
    Replies:
    0
    Views:
    152
    John Stoffel
    Feb 6, 2009
  5. Davy
    Replies:
    2
    Views:
    209
Loading...

Share This Page