我正在编写一个matlab脚本,该脚本递归地遍历一个目录,并尝试查找特定类型的所有文件。我使用一个数组作为一种堆栈。
这条线
dirstack{end + 1} = filesInCurrentDir(i);失败。但是,如果我使用dbstop if error并逐字手动运行完全相同的行,它就可以很好地工作。
如果我为length(dirstack) + 1预先分配了一个索引,它也会失败
这在脚本环境中不起作用,但在交互环境中却能起作用,这有什么原因吗?
最小工作示例:
DIR='.';
dirstack{1} = DIR;
while length(dirstack) ~= 0 %loop while there's still directories to look for
curdir = dirstack{1}; %the working directory is popped off the top of the stack
dirstack{1} = []; %delete the top element, finishing the pop operation
filesInCurrentDir = dir(curdir);
for i=3:length(filesInCurrentDir) % start at 3, dir returns 1:. 2:.. and we don't want those
if filesInCurrentDir(i).isdir; %if this is a directory
dirstack{end+1} = filesInCurrentDir(i);
elseif strcmp(filesInCurrentDir(i).name(end+[-3:0], '.jpg')) == 1 %if it's a psdata file
files{end+1} = [curdir, filesep, filesInCurrentDir(i_.name)];
end
end
end发布于 2017-06-01 03:50:19
这是我如何获取当前文件夹及其子文件夹下的所有.jpg文件的方法:
dirs = genpath(pwd); % dir with subfolders
dirs = strsplit(dirs, pathsep); % in cellstr for each dir
files = {};
for i = 1:numel(dirs)
curdir = [dirs{i} filesep];
foo = dir([curdir '*.jpg']); % all jpg files
foo([foo.isdir]) = []; % just in case .jpg is folder name
foo = strcat(curdir, {foo.name}); % full file names
files = [files foo]; % cell growing
end现在回到你的问题上。代码中有几个地方有错误。您可以与我更正的代码进行比较,并检查我在代码中的注释:
dirstack = {pwd}; % ensure init dirstack to current dir
files = {};
while length(dirstack) ~= 0 % better ~isempty(dirstack)
curdir = dirstack{1};
dirstack(1) = []; % dirstack{1} = [] sets first cell to [], wont remove the cell as you want
filesInCurrentDir = dir(curdir);
for i=3:length(filesInCurrentDir) % this works for Windows, but may not be safe to always skip first two
if filesInCurrentDir(i).isdir
dirstack{end+1} = filesInCurrentDir(i);
elseif strcmp(filesInCurrentDir(i).name(end+[-3:0]), '.jpg') == 1 % had error here
files{end+1} = [curdir, filesep, filesInCurrentDir(i).name]; % had error here
end
end
endhttps://stackoverflow.com/questions/44292836
复制相似问题