return to misc index

This Tcl script provides a procedure for returning the contents of a target directory by name and size. The full path name and the size, in bytes, of each item in a target directory are appended to a list supplied by the user.

Note: this procedure does not recursively list the contents of the subdirectories of the target directory. For examples of recursion refer to dirsize.tcl and getfiles.tcl.

Listing 1

proc listsizes { dir } {
    set contents [glob -directory $dir *]
    set dirlist ""
    set filelist ""
    foreach item $contents {
       set bytes [file size $item]
       set name [file tail $item]
       if { [file isdirectory $item] } {
           set name /$name
       set temp [format "%8d %s\n" $bytes $name]
       if { [file isdirectory $item] } {
          append dirlist $temp
       } else {
          append filelist $temp
    append out $dirlist
    append out $filelist
    return $out

The input parameters are:

    dir    the full path of the directory to be listed
To list the sizes of the sub-directories and files in
a directory the listsizes procedure might be used by 
another Tcl script as follows.
    source /Users/Documents/TCL/listsizes.tcl
    # print the directory listing to the console
    set files [listsizes /Users/Documents]
    puts "$files"

The output would look (something) like this,
     884 /WebSite
     306 /wip_fall2002
     272 /wip_fall2002_October
 6277120 3Delight.pkg.tar
17407813 Acrobat Reader Installer
Note the use of the source command to "point" the 
Tcl interpreter at the directory containing
the listsizes.tcl script.

© 2002- Malcolm Kesson. All rights reserved.