return to misc index

This Tcl script provides a procedure for listing files with a specified extension. The procedure does not examine the subdirectories of the target directory.

Listing 1

proc dirlist { dir ext } {
    set contents [glob -directory $dir *$ext]
    foreach item $contents {
       append out $item
       append out "\n"
    return $out

The input parameters are:

    dir    the full path of the directory to be listed
    ext    the extension of the files to appear in the
A directory called "frames" contains a sequence of 
TIFF files. Assume it is located at 
To list only the "tif" files in this directory the 
dirlist procedure might be used by another Tcl
script as follows.
    source /Users/Documents/TCL/dirlist.tcl
    # print the directory listing to the console
    set files [dirlist /Users/Documents/frames .tif]
    puts "$files"

The output would look like this,

Under Windows the script would be invoked as follows. In particular
notice the use of the forward slash even though under Windows we would
normally use a back slash as a separator when specifying a path.
    source H:tcl/dirlist.tcl
    set files [dirlist H:/frames .tif]
    puts "$files"
Note the use of the source command to "point" the 
Tcl interpreter at the directory containing
the listfiles.tcl script.

© 2002- Malcolm Kesson. All rights reserved.