Returning file names from a directory and sub-directory

9 visualizaciones (últimos 30 días)
Matthew
Matthew el 5 de Nov. de 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 comentario
Matthew
Matthew el 5 de Nov. de 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

Iniciar sesión para comentar.

Respuestas (1)

Image Analyst
Image Analyst el 5 de Nov. de 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.

Categorías

Más información sobre Search Path en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by