Directory Tree (code snippet)

Description

Used in conjunction with a for loop to read all files in a subdirectory.

In normal usage attr.mode will be 'file' for a file and 'directory' for a directory, if you are working with "foreign" directories on mapped drives such as Mac or Linux partitions, file names with characters which are illegal for windows will throw an error getting the attributes and the attr.mode will be 'attrfail'

Requires: lfs

Code

dir_tree.fh_lua
function dirtree(dir)
    assert(dir and dir ~= "", "directory parameter is missing or empty")
    if string.sub(dir, -1) == "/" then
        dir=string.sub(dir, 1, -2)
    end
    local function yieldtree(dir)
        for entry in lfs.dir(dir) do
            if entry ~= "." and entry ~= ".." then
                entry=dir.."\\"..entry
                local attr,err=lfs.attributes(entry)
                if attr == nil then attr = {mode='attrfail',error=err} end
                coroutine.yield(entry,attr)
                if attr.mode == "directory" then
                    yieldtree(entry)
                end
            end
        end
    end
    return coroutine.wrap(function() yieldtree(dir) end)
end

Usage

require 'lfs'
pluginDir = 'd:\\temp\\fhbackup'
for filename,attr in dirtree(pluginDir) do
    if attr.error then
        print('filename:'..filename..' caused error '..attr.error)
    else
        if attr.mode == 'file' then
            print(filename)
        end
    end
end