Skip to main content

directory

directory Function

Syntax:

directory pathspec &key → pathnames

Arguments and Values:

pathspec—a pathname designator , which may contain wild components.

pathnames—a list of physical pathnames.

Description:

Determines which, if any, files that are present in the file system have names matching pathspec, and returns a fresh list of pathnames corresponding to the truenames of those files.

An implementation may be extended to accept implementation-defined keyword arguments to directory.

Affected By:

The host computer’s file system.

Exceptional Situations:

If the attempt to obtain a directory listing is not successful, an error of type file-error is signaled.

See Also:

pathname, logical-pathname, ensure-directories-exist, Section 20.1 (File System Concepts), Section 21.1.1.1.2 (Open and Closed Streams), Section 19.1.2 (Pathnames as Filenames)

Notes:

If the pathspec is not wild, the resulting list will contain either zero or one elements.

Common Lisp specifies “&key” in the argument list to directory even though no standardized keyword arguments to directory are defined. “:allow-other-keys t” may be used in conforming programs in order to quietly ignore any additional keywords which are passed by the program but not supported by the implementation.

Expanded Reference: directory

Listing files matching a wildcard pattern

directory returns a list of pathnames for files matching the given wildcard pattern. The results are truenames (physical pathnames).

;; List all .lisp files in /tmp (if any exist)
(directory #P"/tmp/*.lisp")
;; => (#P"/tmp/test.lisp" #P"/tmp/utils.lisp") ; implementation-dependent

Non-wild pathspec returns zero or one matches

If the pathspec contains no wildcards, the result is either an empty list or a list with one element.

;; Check for a specific file
(directory #P"/tmp/nonexistent-file-xyz.txt")
=> ()

;; An existing file returns a one-element list
(with-open-file (s "/tmp/cl-dir-test.txt" :direction :output
:if-exists :supersede)
(write-string "test" s))
(directory #P"/tmp/cl-dir-test.txt")
=> (#P"/tmp/cl-dir-test.txt")

Using :wild-inferiors for recursive listing

Use :wild-inferiors in the directory component to match files in subdirectories recursively.

;; List all .lisp files under a directory tree
(directory (make-pathname :directory '(:absolute "home" "user" :wild-inferiors)
:name :wild
:type "lisp"))
;; => (...) ; implementation-dependent

The result is always a fresh list

Each call to directory returns a new list, even for the same pattern.

(let ((a (directory #P"/tmp/*.txt"))
(b (directory #P"/tmp/*.txt")))
(eq a b))
=> NIL