【问题标题】:Directory recursive traversal does not go beyond 2 levels in Matlab目录递归遍历在 Matlab 中不超过 2 个级别
【发布时间】:2013-01-12 11:32:48
【问题描述】:

目录递归遍历不超过2级。 为什么会这样?

==================================================== =========== currentFolderDir = '.'; % 密码 % path('C:\Users\EI\Documents\MATLAB\OO\面向对象的简单对象创建'); 深度等级 = 0; 文件夹计数 = 0; 文件计数 = 0; fprintf('======================================\n'); fprintf('深度等级:%d\n', depthLevel); [folderCount, fileCount] = fileDirectoryRecursiveTraversal (currentFolderDir, depthLevel, folderCount, fileCount); ==================================================== =========== 函数 [folderCount, fileCount] = fileDirectoryRecursiveTraversal (currentFile, depthLevel, folderCount, fileCount) 对于 i = 1:depthLevel fprintf('\t\t'); 结尾 fprintf('%s\n', currentFile); % 打印条目的名称 %isdir(currentFile) % [ERR] 不能超过 2 级 %暂停; if (isdir(currentFile)) % 检查是否为目录 文件夹计数 = 文件夹计数 + 1; fprintf('\n有 %d 个文件夹。\n', folderCount); 暂停 depthLevel = depthLevel + 1; fprintf('======================================\n'); fprintf('深度等级:%d\n', depthLevel); % 获取目录中所有条目的列表 条目 = 目录(当前文件); % 条目 (1).name = '.' % 条目 (2).name = '..' numberOfEntries = 长度(条目); % 包括当前文件夹和指向上一级文件夹的指针 % 确保列表不为空 % if( (numberOfEntries - 2) ~= 0 ) % 2: % entries(1).name = '.'; % 条目 (2).name = '..' if(numberOfEntries ~= 2) % 遍历所有条目 对于 i = 3:numberOfEntries % 递归调用遍历 [folderCount, fileCount] = fileDirectoryRecursiveTraversal( entries(i).name, depthLevel, folderCount, fileCount); % i = 3:numberOfEntries 结尾 fprintf('\n深度等级:%d\n', depthLevel); fprintf('有 %d 个文件。\n\n', fileCount); 文件计数 = 0; 别的 % disp('cccccccccccccccccccc') 文件计数 = 0; % 空文件夹 结尾 别的 文件计数 = 文件计数 + 1; 文件夹计数 = 0; 结尾 文件夹计数 = 文件夹计数 - 1; depthLevel = depthLevel - 1; % 退出水平 结尾

【问题讨论】:

  • 试试 currentFolderDir =pwd
  • 正如评论的那样,它被尝试过,但它也没有工作。
     条目 = dir(currentFile); length(entries) 
    在第二级的深度显示“0”,这是不正确的行为。
  • 您没有将目录添加到文件中。你应该使用fullfile(currentFile,entries(i).name) - 否则matlab找不到目录。

标签: matlab directory traversal


【解决方案1】:

我已经调整了一个函数,用于递归处理某个目录中的文件。它正确遍历所有子目录并显示文件名,但不显示深度级别、文件夹计数和文件计数。它应该很容易适应,但如果您需要帮助,请告诉我:

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

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2013-01-23
    • 2012-08-22
    相关资源
    最近更新 更多