recursion - tcl 深度递归文件搜索,搜索扩展名为 *.c 的文件

标签 recursion tcl file-search

使用旧答案在 tcl 中搜索文件:
https://stackoverflow.com/a/435094/984975

首先让我们讨论一下我现在在做什么:
使用此功能:(归功于 Jacson)

# findFiles
# basedir - the directory to start looking in
# pattern - A pattern, as defined by the glob command, that the files must match
proc findFiles { basedir pattern } {

    # Fix the directory name, this ensures the directory name is in the
    # native format for the platform and contains a final directory seperator
    set basedir [string trimright [file join [file normalize $basedir] { }]]
    set fileList {}

    # Look in the current directory for matching files, -type {f r}
    # means ony readable normal files are looked at, -nocomplain stops
    # an error being thrown if the returned list is empty
    foreach fileName [glob -nocomplain -type {f r} -path $basedir $pattern] {
        lappend fileList $fileName
    }

    # Now look for any sub direcories in the current directory
    foreach dirName [glob -nocomplain -type {d  r} -path $basedir *] {
        # Recusively call the routine on the sub directory and append any
        # new files to the results
        set subDirList [findFiles $dirName $pattern]
        if { [llength $subDirList] > 0 } {
            foreach subDirFile $subDirList {
                lappend fileList $subDirFile
            }
        }
    }
    return $fileList
 }

并调用以下命令:
findFiles some_dir_name *.c

目前的结果:
bad option "normalize": must be atime, attributes, channels, copy, delete, dirname, executable, exists, extension, isdirectory, isfile, join, lstat, mtime, mkdir, nativename, owned, pathtype, readable, readlink, rename, rootname, size, split, stat, tail, type, volumes, or writable

现在,如果我们运行:
glob *.c

我们得到了很多文件,但它们都在当前目录中。

目标是获取机器上所有子文件夹中的所有文件及其路径。
有谁能帮忙吗?

我真正想做的是找到*.c 文件数最多的目录。
但是,如果我可以列出所有文件及其路径,我就可以计算每个目录中有多少个文件并获得计数最高的文件。

最佳答案

您正在使用旧版本的 Tcl。 [file normalize]大约在 2002 年左右在 Tcl 8.4 中引入。已经升级了

如果你不能 - 那么你使用 glob 但只为文件调用一次,然后遍历目录。见 glob -types选项。

这是一个演示:

proc on_visit {path} {
    puts $path
}

proc visit {base glob func} {
    foreach f [glob -nocomplain -types f -directory $base $glob] {
        if {[catch {eval $func [list [file join $base $f]]} err]} {
            puts stderr "error: $err"
        }
    }
    foreach d [glob -nocomplain -types d -directory $base *] {
        visit [file join $base $d] $glob $func
    }
}

proc main {base} {
    visit $base *.c [list on_visit]
}

main [lindex $argv 0]

关于recursion - tcl 深度递归文件搜索,搜索扩展名为 *.c 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104940/

相关文章:

java - 这个递归是如何工作的以及如何让它打印出根?

java - 递归:解决进口迷宫?

file - .net 中的递归文件搜索

image - 通过Powershell进行智能图像搜索

c# - Google Drive API v3 (C# .NET) 按标题搜索文件夹/文件时抛出 RequestError Invalid Value [400]

ruby - 如何从 Net-SFTP 结果创建文件/目录树?

algorithm - 在迷宫中寻找输出的死胡同填充算法是否被视为回溯算法?

parameters - TCL 中的反斜杠是什么意思?

function - 为什么Tcl变量命令总是返回一个空字符串?

bash - 如何在期望中转义方括号?