s c h e m a t i c s : c o o k b o o k

/ Cookbook.FileWalkDirectoryTree

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Walking Directory Trees

Problem

You need to look at every file in a directory, or an entire directory tree, that matches a given pattern.

Solution

find-files in the mzlib file.ss library is a very flexible way to do this. find-files takes 2 arguments, a one argument function that accepts a file name (full path) and returns #t if the file should be included in the result list, and the path to root the search at. If you omit the 2nd argument, or specify #f, find-files starts at the current directory. A few examples:

; list all files and directories under /tmp
(find-files (lambda (x) x) "/tmp")
; list all subdirectories of /tmp
(find-files (lambda (x) (directory-exists? x)) "/tmp")
; list all files with extension .scm under /tmp
(find-files 
  (lambda (x) 
    (and (equal? (filename-extension x) "scm")
         (not (directory-exists? x)))) 
  "/tmp")
; list all files under /tmp that are > 1024 bytes
(find-files 
   (lambda (x) (and (not (directory-exists? x))
                    (> (file-size x) 1024)))
   "/tmp")

Discussion

The examples given all just act on metadata of the file, there's no reason you can't inspect the contents of the file in the filter function, though that will make find-files much slower. Also, it can be a little tricky to get find-files to not recurse directory trees, at least on Windows. Generally, you include a directory-exists? test in your filter:

; list files only in the \windows directory, don't recurse directories.
(find-files 
   (lambda (x) 
     (and (not (directory-exists? x))
          (equal? (path-only x) "\\windows\\"))) 
   "\\windows")

fold-files, also in file.ss is a more powerful version of find-files.

-- GordonWeakliem - 29 Apr 2004

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest