更新:
考虑到这篇文章已经很老了,而且我已经修改了很多实用程序供我自己使用,我想我应该发布一个新版本。我的最新代码可以在
The MathWorks File Exchange
:
dirPlus.m
. 你也可以从
GitHub
.
我做了一些改进。现在,您可以选择预先设置完整路径或只返回文件名(从
Doresoom
和
Oz Radiano
)并将正则表达式模式应用于文件名(从
Peter D
)此外,我还添加了对每个文件应用验证功能的功能,允许您根据标准而不仅仅是文件名(即文件大小、内容、创建日期等)来选择它们。
注:
在较新版本的Matlab(R2016B及更高版本)中,
dir
函数具有递归搜索功能!这样你就可以得到所有
*.m
当前文件夹的所有子文件夹中的文件:
dirData = dir('**/*.m');
旧密码:(后人用)
下面是一个函数,它递归搜索给定目录的所有子目录,收集它找到的所有文件名的列表:
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
在将上述函数保存到Matlab路径的某个位置后,可以按以下方式调用它:
fileList = getAllFiles('D:\dic');