MATLAB遍历文件夹下所有文件

先给出函数

function [ files ] = scanDir( root_dir )

files={};
if root_dir(end)~='/'
 root_dir=[root_dir,'/'];
end
fileList=dir(root_dir);  %扩展名
n=length(fileList);
cntpic=0;
for i=1:n
    if strcmp(fileList(i).name,'.')==1||strcmp(fileList(i).name,'..')==1
        continue;
    else
        fileList(i).name
        if ~fileList(i).isdir % 如果不是目录则跳过
            
            full_name=[root_dir,fileList(i).name];
            
                 cntpic=cntpic+1;
                 files(cntpic)={full_name};
%              end
        else
            files=[files,scanDir([root_dir,fileList(i).name])];
        end
    end
end

end

测试文件夹如下所示:

 

文件夹1如下所示:(文件夹1里面的新建文件夹有3个图片,文件夹1共10个文件)

文件夹2如下所示:(文件夹2共2个文件)

测试:

files=scanDir('C:\Users\yangsu\Desktop\test2');

得到一个1×12cell的数据

 

posted @ 2017-07-19 21:33  _云深不知处  阅读(22143)  评论(0编辑  收藏  举报