ZetCode

Scheme directories

last modified November 25, 2026 Guile 3.0

A directory is a file that holds names of other files and directories, which together form a tree. The files article reads, writes, and deletes single files; this article creates and removes directories, lists their contents, reads file information, and walks whole trees. GNU Guile provides the POSIX directory procedures in its core and tree walking in the (ice-9 ftw) module. The examples run with GNU Guile 3.0.7 in a directory named scheme, which contains a small data tree.

The current directory

Relative file names are resolved against the current working directory. getcwd returns it as an absolute path, and chdir changes it for the rest of the program.

cwd.scm
(define (show-directory)
  (display "in ")
  (display (basename (getcwd)))
  (newline))

(show-directory)
(chdir "data")
(show-directory)
(display (file-exists? "notes.txt"))
(newline)
(chdir "..")
(show-directory)

show-directory prints only the last component of the path, which basename extracts; the full path depends on where the examples are stored. After chdir, the name notes.txt refers to the file inside data. ".." is the parent directory. Like environment variables, the current directory belongs to the process, so the shell stays where it was.

$ guile cwd.scm
in scheme
in data
#t
in scheme

Creating and removing directories

mkdir creates a directory, rmdir removes an empty one, and file-is-directory? tells a directory from other files. Both procedures raise an error when the operation fails.

making.scm
(use-modules (ice-9 exceptions))

(define (report name)
  (display name)
  (display (cond ((not (file-exists? name)) ": missing")
                 ((file-is-directory? name) ": directory")
                 (else ": file")))
  (newline))

(define (try-mkdir name)
  (guard (e ((error? e)
             (display "cannot create ")
             (display name)
             (display ": ")
             (display (car (exception-irritants e)))
             (newline)))
    (mkdir name)))

(try-mkdir "reports")
(report "reports")
(report "data/notes.txt")
(try-mkdir "reports")
(try-mkdir "drafts/2026")
(rmdir "reports")
(report "reports")

report checks whether a name exists and whether it is a directory. try-mkdir catches the error with guard and prints the message of the operating system. Creating a directory that exists fails, and so does creating drafts/2026, because mkdir does not create the missing parent drafts. At the end, rmdir removes the new directory.

$ guile making.scm
reports: directory
data/notes.txt: file
cannot create reports: File exists
cannot create drafts/2026: No such file or directory
reports: missing

Reading directory entries

opendir opens a directory stream, readdir returns one entry name at a time and an end-of-file object at the end, and closedir closes the stream. The pattern is the same as reading lines from a port.

entries.scm
(define (directory-entries dir)
  (let ((stream (opendir dir)))
    (let loop ((entry (readdir stream)) (acc '()))
      (if (eof-object? entry)
          (begin
            (closedir stream)
            (reverse acc))
          (loop (readdir stream) (cons entry acc))))))

(for-each (lambda (name)
            (display name)
            (newline))
          (directory-entries "data"))

directory-entries collects the names into a list. The list contains . and .., which every directory has, and the hidden file .settings. The entries come in the order in which the file system stores them, not in alphabetical order, so the output may differ on another system.

$ guile entries.scm
.
archive
.settings
notes.txt
todo.txt
photo.png
..

Sorted and filtered listings

scandir from (ice-9 ftw) does the loop itself and returns the names sorted. An optional predicate selects the names to keep.

scanning.scm
(use-modules (ice-9 ftw))

(display (scandir "data"))
(newline)

(define (visible? name)
  (not (string-prefix? "." name)))

(display (scandir "data" visible?))
(newline)

(define (text-file? name)
  (string-suffix? ".txt" name))

(display (scandir "data" text-file?))
(newline)

The first call returns every entry. The sorting follows the rules of the current locale, which ignore the leading dot, so .settings sits between photo.png and todo.txt. visible? leaves out the names that start with a dot, which also removes . and .., and text-file? keeps the names that end in .txt. Both predicates receive only the name, not the full path.

$ guile scanning.scm
(. .. archive notes.txt photo.png .settings todo.txt)
(archive notes.txt photo.png todo.txt)
(notes.txt todo.txt)

File information

stat returns information about a file: its type, size, permissions, owner, and times. Accessors such as stat:type, stat:size, and stat:perms read the fields.

details.scm
(use-modules (ice-9 ftw) (ice-9 format))

(define (visible? name)
  (not (string-prefix? "." name)))

(define (show-details dir name)
  (let ((info (stat (string-append dir "/" name))))
    (format #t "~a: ~a, mode ~a"
            name
            (stat:type info)
            (number->string (stat:perms info) 8))
    (when (eq? (stat:type info) 'regular)
      (format #t ", ~d bytes" (stat:size info)))
    (newline)))

(for-each (lambda (name) (show-details "data" name))
          (scandir "data" visible?))

scandir returns names, so show-details builds the path with string-append before calling stat. stat:type returns a symbol such as regular or directory, and the permissions are shown in octal as in the chmod command; they depend on the umask of the user who created the files. The size of a directory says little about its contents, so it is printed only for regular files. stat:mtime returns the time of the last change in seconds since 1970.

$ guile details.scm
archive: directory, mode 775
notes.txt: regular, mode 664, 60 bytes
photo.png: regular, mode 664, 1500 bytes
todo.txt: regular, mode 664, 48 bytes

A directory tree

A directory can contain other directories, so walking a whole tree is a natural task for recursion. The procedure lists a directory and calls itself for every subdirectory.

tree.scm
(use-modules (ice-9 ftw))

(define (visible? name)
  (not (string-prefix? "." name)))

(define (show-tree dir depth)
  (for-each
   (lambda (name)
     (let ((path (string-append dir "/" name)))
       (display (make-string (* depth 2) #\space))
       (display name)
       (cond ((file-is-directory? path)
              (display "/")
              (newline)
              (show-tree path (+ depth 1)))
             (else
              (display " (")
              (display (stat:size (stat path)))
              (display " bytes)")
              (newline)))))
   (scandir dir visible?)))

(display "data/")
(newline)
(show-tree "data" 1)

show-tree indents each name by two spaces per level. A directory gets a slash and its contents follow below it, one level deeper; a file gets its size. Because scandir sorts each directory, the output is the same on every system.

$ guile tree.scm
data/
  archive/
    2025/
      report.txt (51 bytes)
    old-notes.txt (26 bytes)
  notes.txt (60 bytes)
  photo.png (1500 bytes)
  todo.txt (48 bytes)

Folding over a tree

file-system-fold walks a tree and combines the files into a result, like fold combines the elements of a list. It takes six procedures, the initial result, and the starting directory. enter? decides whether to descend into a directory, leaf is called for each file, down and up when the walk enters and leaves a directory, skip for directories that enter? refused, and error for entries that cannot be read. Each procedure receives the current result and returns the new one.

totals.scm
(use-modules (ice-9 ftw) (ice-9 format))

;; the result is a list: (files directories bytes skipped)
(define (add-file result size)
  (list (+ (car result) 1) (cadr result)
        (+ (caddr result) size) (cadddr result)))

(define (add-directory result)
  (list (car result) (+ (cadr result) 1)
        (caddr result) (cadddr result)))

(define (add-skipped result)
  (list (car result) (cadr result)
        (caddr result) (+ (cadddr result) 1)))

(define (totals dir skip-name)
  (file-system-fold
   (lambda (name stat result)                 ; enter?
     (not (string=? (basename name) skip-name)))
   (lambda (name stat result)                 ; leaf
     (add-file result (stat:size stat)))
   (lambda (name stat result)                 ; down
     (add-directory result))
   (lambda (name stat result) result)         ; up
   (lambda (name stat result)                 ; skip
     (add-skipped result))
   (lambda (name stat errno result) result)   ; error
   '(0 0 0 0)
   dir))

(define (report label result)
  (format #t "~a: files ~d, directories ~d, bytes ~d, skipped ~d~%"
          label (car result) (cadr result) (caddr result) (cadddr result)))

(report "everything" (totals "data" ""))
(report "without archive" (totals "data" "archive"))

The result is a list of four counters, which the three add- helpers update. totals skips the directories with a given name; with an empty name nothing is skipped. The walk includes hidden files, so the first total counts .settings too, and the starting directory itself is counted as a directory. The second call does not enter archive and counts it as skipped. The procedures receive full paths, so basename extracts the directory name.

$ guile totals.scm
everything: files 6, directories 3, bytes 1697, skipped 0
without archive: files 4, directories 1, bytes 1620, skipped 1

Deleting a tree

rmdir removes only empty directories. To delete a directory with its contents, a program first deletes everything inside it, deepest entries first.

cleanup.scm
(use-modules (ice-9 ftw) (ice-9 exceptions))

(define (touch path)
  (call-with-output-file path
    (lambda (port) (display "temporary" port))))

(define (make-tree)
  (mkdir "scratch")
  (mkdir "scratch/a")
  (mkdir "scratch/a/b")
  (touch "scratch/one.txt")
  (touch "scratch/a/two.txt")
  (touch "scratch/a/b/three.txt"))

(define (real-entry? name)
  (not (member name '("." ".."))))

(define (delete-tree path)
  (if (eq? (stat:type (lstat path)) 'directory)
      (begin
        (for-each (lambda (name)
                    (delete-tree (string-append path "/" name)))
                  (scandir path real-entry?))
        (rmdir path))
      (delete-file path))
  (display "removed ")
  (display path)
  (newline))

(make-tree)
(guard (e ((error? e)
           (display "rmdir scratch: ")
           (display (car (exception-irritants e)))
           (newline)))
  (rmdir "scratch"))
(delete-tree "scratch")
(display (file-exists? "scratch"))
(newline)

make-tree creates a small tree, and the first attempt to remove it with rmdir fails. delete-tree then calls itself on each entry before it removes the directory. It uses lstat rather than stat: for a symbolic link, lstat describes the link itself, while stat and file-is-directory? follow it. Following a link to a directory would delete files outside the tree, so a link is removed with delete-file like a file. Like rm -r, the procedure deletes without asking.

$ guile cleanup.scm
rmdir scratch: Directory not empty
removed scratch/a/b/three.txt
removed scratch/a/b
removed scratch/a/two.txt
removed scratch/a
removed scratch/one.txt
removed scratch
#f

A disk usage tool

The last example prints how many bytes each entry of a directory takes, counting subdirectories with all their contents, similar to the Unix du tool. The directory comes from the command line.

usage.scm
(use-modules (ice-9 ftw) (ice-9 format))

(define (tree-size path)
  (file-system-fold
   (lambda (name stat result) #t)
   (lambda (name stat result) (+ result (stat:size stat)))
   (lambda (name stat result) result)
   (lambda (name stat result) result)
   (lambda (name stat result) result)
   (lambda (name stat errno result) result)
   0
   path))

(define (real-entry? name)
  (not (member name '("." ".."))))

(define dir
  (if (null? (cdr (command-line)))
      "."
      (cadr (command-line))))

(define sizes
  (map (lambda (name)
         (cons name (tree-size (string-append dir "/" name))))
       (scandir dir real-entry?)))

(for-each (lambda (entry)
            (format #t "~a~a~a~%"
                    (cdr entry) #\tab (car entry)))
          sizes)
(format #t "~a~atotal~%" (apply + (map cdr sizes)) #\tab)

tree-size uses file-system-fold with a single number as the result; only leaf changes it. file-system-fold also accepts a regular file, which it passes to leaf, so the same procedure measures files and directories. The program adds up the sizes of the file contents, while du also counts the space taken by directories and rounds to disk blocks, so its numbers are larger. A tab separates the columns.

$ guile usage.scm data
77	archive
60	notes.txt
1500	photo.png
12	.settings
48	todo.txt
1697	total
$ guile usage.scm data/archive
51	2025
26	old-notes.txt
77	total

Source

File System — GNU Guile Reference Manual

File Tree Walk — GNU Guile Reference Manual

In this article we have changed the current directory, created and removed directories, read directory entries with opendir and readdir, listed them sorted and filtered with scandir, read file information with stat, printed a directory tree, computed totals with file-system-fold, deleted a tree, and measured disk usage. The recursion article explains the technique behind the tree walks, and the command-line arguments article the reading of the directory name.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.