Careful when using chdir inside a dirEntries loop

Andrej Mitrovic none at none.none
Thu Jun 9 15:20:03 PDT 2011


Here's a little buggy code which most often throws an exception:

    foreach (string entry; dirEntries(curdir, SpanMode.shallow))
    {
        if (entry.isdir)
        {
            foreach (string subentry; dirEntries(entry, SpanMode.shallow))
            {
                if (subentry.isdir)
                {
                    chdir(rel2abs(subentry));
                }
            }
        }
    }

Usually throws something like:
std.file.FileException at std\file.d(1124): .\foo\bar.d: The system cannot find the path specified.

The problem is, chdir will modify curdir and dirEntries doesn't store 'curdir' internally as an absolute address.

The way to work around this is to call rel2abs as soon as possible when using 'curdir' (the first line changed):

    foreach (string entry; dirEntries(rel2abs(curdir), SpanMode.shallow))
    {
        if (entry.isdir)
        {
            foreach (string subentry; dirEntries(entry, SpanMode.shallow))
            {
                if (subentry.isdir)
                {
                    chdir(rel2abs(subentry));
                }
            }
        }
    }

I've had a use for code like this because where I was invoking a batch file which was always relative to the current subdirectory. But anyways, I just thought I'd throw it out in case anyone else runs into this.


More information about the Digitalmars-d-learn mailing list