Tuesday, July 22, 2008

Recursive Directory Function Execution

A simple function that provides a large amount of flexibility in its use.

DirectoryRecurse

% directoryRecurse - Recurse through sub directories executing function pointer
%===============================================================================
% Description : Recurses through each directory, passing the full directory
% path and any extraneous arguments (varargin) to the specified
% function pointer
%
% Parameters : directory - Top level directory begin recursion from
% function_pointer - function to execute with each directory as
% its first argument
% varargin - Any extra arguments that should be passed
% to the function pointer.
%
% Call Sequence : directoryRecurse(directory, function_pointer, varargin)
%
% IE: To execute the 'rmdir' command with the 's' parameter over
% 'c:\tmp' and all subdirectories
%
% directoryRecurse('c:\tmp', @rmdir, 's')
%
% Author : Rodney Thomson
% http://iheartmatlab.blogspot.com
%===============================================================================
function directoryRecurse(directory, function_pointer, varargin)

contents = dir(directory);
directories = find([contents.isdir]);

% For loop will be skipped when directory contains no sub-directories
for i_dir = directories

sub_directory = contents(i_dir).name;
full_directory = fullfile(directory, sub_directory);

% ignore '.' and '..'
if (strcmp(sub_directory, '.') || strcmp(sub_directory, '..'))
continue;
end

% Recurse down
directoryRecurse(full_directory, function_pointer, varargin{:});
end

% execute the callback with any supplied parameters.
% Due to recursion will execute in a bottom up manner
function_pointer(directory, varargin{:});
end

The directoryRecurse function finds all directories below the supplied directory and executes the supplied function with the full directory path as the first argument. Any extra arguments supplied to directoryRecurse are passed onto the function supplied in function_pointer.

Its a hard concept to explain with words, so here are a few useful examples:

% add current directory and any sub-directory to the Matlab search path
directoryRecurse(pwd, @addpath);

% delete all contents of 'c:\tmp', requires passing the 's' flag to the rmdir function
directoryRecurse('c:\tmp', @rmdir, 's')

3 comments:

  1. Rodney-

    You can avoid varargin in your function and have that info, if needed, be supplied by the user in their function handle. Instead of passing in a "naked" handle, they can then pass in an anonymous function which contains all the extra calling parameters. In that way, you will have flexibility to update your directory recursion function with extra inputs in the future, should you wish to do so.

    --Loren

    ReplyDelete
  2. Thank you very much! looking for this
    Ali

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete