File Exchange

image thumbnail

DIRWALK - Walk the directory tree

version 1.1.0.0 (4.1 KB) by Evgeny Pr
Generate the file names and dir names in a directory tree by walking the tree.

4 Downloads

Updated 10 Jul 2011

View Version History

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.

Cite As

Evgeny Pr (2020). DIRWALK - Walk the directory tree (https://www.mathworks.com/matlabcentral/fileexchange/32036-dirwalk-walk-the-directory-tree), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (4)

med-sweng

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

Josiah McClurg

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

MATLAB Release Compatibility
Created with R2009b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!