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. 效果