Code covered by the BSD License  

Highlights from
DIRWALK - Walk the directory tree

4.0

4.0 | 1 rating Rate this file 12 Downloads (last 30 days) File Size: 4.1 KB File ID: #32036

DIRWALK - Walk the directory tree

by Evgeny Pr

 

03 Jul 2011 (Updated 10 Jul 2011)

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

| Watch this File

File Information
Description

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.

MATLAB release MATLAB 7.9 (2009b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (1)
31 May 2012 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

Please login to add a comment or rating.
Updates
10 Jul 2011

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

Tag Activity for this File
Tag Applied By Date/Time
dir Evgeny Pr 05 Jul 2011 11:10:55
walk Evgeny Pr 05 Jul 2011 11:10:55
dir walk Evgeny Pr 05 Jul 2011 11:10:55
ls Evgeny Pr 05 Jul 2011 11:10:55
dir listing Evgeny Pr 05 Jul 2011 11:10:55
recursive dir Evgeny Pr 05 Jul 2011 11:10:55

Contact us at files@mathworks.com