1. 背景
实现指定文件夹下的指定格式文件遍历,并返回文件路径。
2. 代码实现
function filePaths = searchRoot(root_dir, format) % Inputs: % root_dir: 需要搜索的文件夹的目录路径 % format: 需要过滤识别的文件格式 % Outputs: % filePaths: % Author: HSW % Date: 2018-05-05 % if ~exist('format', 'var') format = '.pgm'; end searchPaths = search(root_dir, format); index = strfind(searchPaths, ','); N = length(index) - 1; filePaths = cell(N, 1); for idx = 1:N filePaths{idx} = searchPaths(index(idx) + 1 : index(idx + 1) - 1); end end function filePaths = search(root_dir, format) % Inputs: % root_dir: 需要搜索的文件夹的目录路径 % format: 需要过滤识别的文件格式 % Outputs: % filePaths: 文件路径用逗号间隔 % Author: HSW % Date: 2018-05-05 % if ~exist('format', 'var') format = '.pgm'; end sub_dirs = dir(root_dir); filePaths = []; for i = 1 : length(sub_dirs) if( isequal( sub_dirs( i ).name, '.' ) || isequal(sub_dirs( i ).name, '..')) continue; end if sub_dirs(i).isdir % 为文件夹时 searchDir = fullfile(root_dir, sub_dirs(i).name); filePathParts = search(searchDir, format); isStart = 0; filePath = []; for idx = 1 : length(filePathParts) if(filePathParts(idx) == ',' && isStart == 0) isStart = 1; continue; elseif(filePathParts(idx) == ',' && isStart == 1) filePaths = [filePaths, ',',filePath]; isStart = 0; filePath = []; elseif(filePathParts(idx) ~= ',' && isStart == 1) filePath = [filePath, filePathParts(idx)]; end end else fileName = sub_dirs(i).name; if isempty(strfind(fileName, format)) continue; else filePath = fullfile(root_dir, sub_dirs(i).name); filePaths = [filePaths, ',', filePath, ',']; end end end end
3. 效果