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')
0 comments:
Post a Comment