File Exchange

image thumbnail

DIRWALK - Walk the directory tree

version 1.1 (4.1 KB) by

Generate the file names and dir names in a directory tree by walking the tree.

4.66667
3 Ratings

7 Downloads

Updated

View License

Function generate the file names and directory names in a directory tree by walking the tree top-down. For each directory in the tree rooted at directory topPath. For each directory of tree you can call "Visitor Function" for files processing.

Using:
    [pathNames, dirNames, fileNames] = dirwalk(topPath)
    dirwalk(topPath, visitor)
    [visitorOutput1, visitorOutput2, ..., visitorOutputN] = dirwalk(topPath, visitor)
    [...] = dirwalk(topPath, visitor, visitorInput1, visitorInput2, ..., visitorInputN)

Example:
    topPath = fullfile(matlabroot, 'toolbox', 'matlab', 'demos');

    % Get files and dirs listing (default visitor)
    [pathNames, dirNames, fileNames] = dirwalk(topPath);
    
    % Call visitor function in each dir
    dirwalk(topPath, @(y,x) disp(strcat(y, filesep, {x.name}')))

See help DIRWALK and TEST_DIRWALK for detailes examples.

Comments and Ratings (3)

Pavel Komarov

%an auxilliary function to find all the leaf directories containing files
%of a given type
function paths = recursedir(pathsofar, type)
paths = [];
dirfiles = dir(pathsofar);
isdirs = [dirfiles(1:end).isdir];

ndx = find(isdirs);%the struct indicies of files that are subdirectories
for i = ndx(3:end)%1 is ., and 2 is .., so definitely skip to keep from going in circles
paths = [paths; recursedir([pathsofar '/' dirfiles(i).name], type)];
end

for i = find(~isdirs)%iterate over files that are not subdirectories
if (strfind(dirfiles(i).name, type))%if contains whatever file extension
paths = [paths; {pathsofar}];%cell array to keep strings separated
break;%don't keep adding the directory to the list
end
end
end

Benjamin I

Benjamin I (view profile)

Functional, but I think it could be more concise and generic. Consider the following 12 lines:

function recurseDirectory(name, callback)
directory = dir(name);
for i = 1:length(directory)
   if(~strcmp(directory(i).name,'.') && ~strcmp(directory(i).name,'..'))
       if(directory(i).isdir)
           recurseDirectory([name '/' directory(i).name], callback);
       else
           callback([name '/' directory(i).name]);
       end
   end
end
end

You can test the above code out with

recurseDirectory('.',@display)

if you like

Updates

1.1

- Fixed bugs
- Added default visitor
- Deleted global variables
- Other improvements

MATLAB Release
MATLAB 7.9 (R2009b)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video