Skip to main content

file-length

file-length Function

Syntax:

file-length stream → length

Arguments and Values:

stream—a stream associated with a file.

length—a non-negative integer or nil.

Description:

file-length returns the length of stream, or nil if the length cannot be determined.

For a binary file, the length is measured in units of the element type of the stream.

Examples:

(with-open-file (s "decimal-digits.text" 


:direction :output :if-exists :error)
(princ "0123456789" s)
(truename s))
→ #P"A:>Joe>decimal-digits.text.1"
(with-open-file (s "decimal-digits.text")
(file-length s))
10

Exceptional Situations:

Should signal an error of type type-error if stream is not a stream associated with a file.

See Also:

open

Expanded Reference: file-length

Basic Usage

file-length returns the length of the file associated with a stream, or NIL if the length cannot be determined.

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

(with-open-file (s "/tmp/cl-fl-test.txt")
(file-length s))
=> 10

Binary File Length

For binary files, the length is measured in units of the element type.

(with-open-file (s "/tmp/cl-fl-test.bin"
:direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(dotimes (i 5) (write-byte i s)))

(with-open-file (s "/tmp/cl-fl-test.bin"
:element-type '(unsigned-byte 8))
(file-length s))
=> 5

Using with file-position

file-length and file-position together enable random access patterns.

(with-open-file (s "/tmp/cl-fl-test.bin"
:element-type '(unsigned-byte 8))
(let ((len (file-length s)))
(file-position s (1- len)) ; seek to last byte
(read-byte s)))
=> 4