Skip to main content

probe-file

probe-file Function

Syntax:

probe-file pathspec → truename

Arguments and Values:

pathspec—a pathname designator .

truename—a physical pathname or nil.

Description:

probe-file tests whether a file exists.

probe-file returns false if there is no file named pathspec, and otherwise returns the truename of pathspec.

If the pathspec designator is an open stream, then probe-file produces the truename of its associated file. If pathspec is a stream, whether open or closed, it is coerced to a pathname as if by the function pathname.

Affected By:

The host computer’s file system.

Exceptional Situations:

An error of type file-error is signaled if pathspec is wild.

An error of type file-error is signaled if the file system cannot perform the requested operation.

See Also:

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

Expanded Reference: probe-file

Testing whether a file exists

probe-file returns the truename of a file if it exists, or nil if it does not.

;; A file that does not exist
(probe-file "/tmp/nonexistent-file-xyz-12345.txt")
=> NIL

Getting the truename of an existing file

When the file exists, probe-file returns its truename as a physical pathname.

(with-open-file (s "/tmp/cl-probe-test.txt" :direction :output
:if-exists :supersede)
(write-string "hello" s))

(probe-file "/tmp/cl-probe-test.txt")
=> #P"/tmp/cl-probe-test.txt"

Using probe-file for conditional file operations

A common pattern is to test for file existence before performing operations.

(let ((path "/tmp/cl-probe-test.txt"))
(if (probe-file path)
(format nil "File ~A exists" path)
(format nil "File ~A does not exist" path)))
=> "File /tmp/cl-probe-test.txt exists"

probe-file works with pathname objects

The argument can be a string, a pathname, or a stream.

(let ((p (make-pathname :directory '(:absolute "tmp")
:name "cl-probe-test"
:type "txt")))
(if (probe-file p) "found" "not found"))
=> "found"