Working with Files and Input/Output in Lisp

June 27, 2024

This post will cover file handling and input/output operations in Lisp. Learn how to read from and write to files, interact with the operating system, and manage external resources in your Lisp programs.

Reading from a File

In Lisp, you can read from a file using the with-open-file macro. This macro opens a file, binds a stream to it, and then executes a body of code. Here’s an example:

(with-open-file (stream <file-path> :direction :input)
(let ((line (read-line stream)))
(format t line)))

In this code snippet, we open a file for reading, read a line from it, and then print the line to the standard output.

Writing to a File

To write to a file in Lisp, you can use the with-open-file macro with the :direction :output parameter. Here’s an example:

(with-open-file (stream <file-path> :direction :output)
(format stream <data-to-write>))

This code snippet opens a file for writing and writes data to it.

Interacting with the Operating System

Lisp provides functions to interact with the operating system. For example, you can use the run-program function to execute external commands. Here’s an example:

(run-program <command> :output *standard-output* :wait t)

This code snippet runs an external command and prints the output to the standard output.

Managing External Resources

When working with files or external resources in Lisp, it’s important to properly manage them to avoid resource leaks. Make sure to close files after reading from or writing to them using the close function.

By understanding file handling and input/output operations in Lisp, you can create programs that interact with external resources efficiently and effectively.