Returning file names from a directory and sub-directory

8 views (last 30 days)
Hi,
I found some code online to return filenames from a directory and it's sub-directories. What would be useful for me would be if the path for each file name is ommitted e.g. insted of C:/My Documented/test.m I just get test.m in the results.
any help much apreciated.
function fileList = getAllFiles(dirName)
dirData = dir(dirName); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dirName,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dirName,subDirs{iDir}); %# Get the subdirectory path
fileList = [fileList; getAllFiles(nextDir)]; %# Recursively call getAllFiles
end
end
  1 Comment
Matthew
Matthew on 5 Nov 2012
I played around and found the answer, simply remove the if ~isempty(fileList) fileList = cellfun(@(x) fullfile(dirName,x),... %# Prepend path to files fileList,'UniformOutput',false); end and it does what i want. hope this may be useful to others.
best wishes

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 5 Nov 2012
Use genpath() to get a list of folders and subfolders. Then use fullfile() and fileparts() as needed for whatever version of the filename you want.

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!