Writing Files in Lisp
Here’s the translation of the Go code example to Lisp, formatted in Markdown suitable for Hugo:
Writing files in Lisp follows similar patterns to the ones we saw earlier for reading.
Try running the file-writing code.
Then check the contents of the written files.
In this Lisp version:
We define a
check
function to handle errors, similar to the Go version.The
main
function contains our file writing operations.We use
with-open-file
to open files for writing, which automatically closes the file when we’re done.Instead of
WriteFile
, we usewith-open-file
with:direction :output
to write a string directly to a file.We use
write-string
to write strings to the file, similar to Go’sWrite
andWriteString
.force-output
is used instead ofSync
to ensure all buffered data is written to the file.We use
with-output-to-string
to create a string buffer, similar to Go’sbufio.NewWriter
.Lisp doesn’t have a direct equivalent to Go’s byte slices, so we use strings instead.
Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the standard input and output streams.