目录递归遍历不超过2个级别。 为什么会这样?
============================================================= currentFolderDir = '.'; % pwd % path('C:\Users\EI\Documents\MATLAB\OO\Simple Object Creation in Object Oriented'); depthLevel = 0; folderCount = 0; fileCount = 0; fprintf('=====================================\n'); fprintf('Depth level: %d\n', depthLevel); [folderCount, fileCount] = fileDirectoryRecursiveTraversal (currentFolderDir, depthLevel, folderCount, fileCount); ============================================================= function [folderCount, fileCount] = fileDirectoryRecursiveTraversal (currentFile, depthLevel, folderCount, fileCount) for i = 1:depthLevel fprintf('\t\t'); end fprintf('%s\n', currentFile ); % Print the name of the entry %isdir(currentFile) % [ERR] can't go beyond level 2 %pause; if (isdir(currentFile)) % Check if it is a directory folderCount = folderCount + 1; fprintf('\nThere are %d folders.\n', folderCount); pause depthLevel = depthLevel + 1; fprintf('=====================================\n'); fprintf('Depth level: %d\n', depthLevel); % Get a list of all the entries in the directory entries = dir(currentFile); % entries(1).name = '.' % entries(2).name = '..' numberOfEntries = length(entries); % including current folder and pointer to folder 1 level up % Ensure that the list is not null % if( (numberOfEntries - 2) ~= 0 ) % 2: % entries(1).name = '.'; % entries(2).name = '..' if(numberOfEntries ~= 2) % Loop over all the entries for i = 3:numberOfEntries % Recursive call to traverse [folderCount, fileCount] = fileDirectoryRecursiveTraversal( entries(i).name, depthLevel, folderCount, fileCount); % i = 3:numberOfEntries end fprintf('\nDepth level: %d\n', depthLevel); fprintf('There are %d files.\n\n', fileCount); fileCount = 0; else % disp('cccccccccccccccccccc') fileCount = 0; % empty folder end else fileCount = fileCount + 1; folderCount = 0; end folderCount = folderCount - 1; depthLevel = depthLevel - 1; % exit level end
答案 0 :(得分:4)
我已经使用了一个函数来递归处理某个目录中的文件。它正确地遍历所有子目录并显示文件名,但它不显示depthlevel,folderCount和fileCount。它应该很容易适应,但如果你需要帮助,请告诉我:
function processDirectory(path)
if ~strcmp(path(end), filesep)
path(end+1)=filesep;
end
dirInfo= dir(path);
files=~[dirInfo.isdir];
fileNames={dirInfo(files).name};
disp(path);
if ~isempty(fileNames)
for i=1:length(fileNames)
% Do whathever (show file names?)
disp(fileNames(i));
end
end
% For each subdir, call itself again
isDir=[dirInfo.isdir];
dirNames={dirInfo(isDir).name};
dirNames(strcmp(dirNames, '.') | strcmp(dirNames, '..'))=[];
for i=1:length(dirNames)
processDirectory([path dirNames{i} filesep]);
end