Returning file names from a directory and sub-directory

조회 수: 9 (최근 30일)
Matthew
Matthew 2012년 11월 5일
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
Matthew
Matthew 2012년 11월 5일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2012년 11월 5일
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.

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by