Returning file names from a directory and sub-directory

9 Ansichten (letzte 30 Tage)
Matthew
Matthew am 5 Nov. 2012
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 Kommentar
Matthew
Matthew am 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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Image Analyst
Image Analyst am 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.

Kategorien

Mehr zu Search Path finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by