Serializing Lisp lists

In Lisp, it is very easy to serialize and deserialize lists into files. You can use the macros with-open-file and print for this. Using macro with-open-file makes sure that the file is closed automatically even in case of failures. The print macro prints lists in a way that they can be read by the Lisp reader. For example, you define the following function for serialization.

(defun serialize (file-name list)
  (with-open-file (stream file-name :direction :output)
    (print list stream)))

You might want to use keyword argument :if-exists :supersede if you want to overwrite existing files. Add another function for deserialization. It uses the read function to read the list back from the file.

(defun deserialize (file-name)
  (with-open-file (stream file-name :direction :input)
    (read stream)))

Now you can use these two functions to save your lists to file and read them back in. I have defined the two functions in a package called mhn-serial.

CL-USER> (mhn-serial:serialize “~/tmp/list.ser” ‘(1 2 3))
(1 2 3)
CL-USER> (mhn-serial:deserialize “/home/neifer/tmp/list.ser”)
(1 3 4)
CL-USER> (car (mhn-serial:deserialize “/home/neifer/tmp/list.ser”))
CL-USER> (cdr (mhn-serial:deserialize “/home/neifer/tmp/list.ser”))
(3 4)
CL-USER> (nth 2 (mhn-serial:deserialize “/home/neifer/tmp/list.ser”))
CL-USER> (mhn-serial:deserialize “/home/neifer/tmp/list.ser”)
((1 2 3) (4 5 6))
CL-USER> (nth 1 (car (cdr (mhn-serial:deserialize “/home/neifer/tmp/list.ser”))))

Please note that I have edited the file between the calls. I have changed the file content from (1 2 3) to (1 3 4) and then to ((1 2 3)(4 5 6)). Just to check if reading works. You could change the content to something more interesting, of course.

CL-USER> (mhn-serial:deserialize “/home/neifer/tmp/list.ser”)
(+ 2 3)
CL-USER> (eval (mhn-serial:deserialize “/home/neifer/tmp/list.ser”))

You see that you have to be very careful when using eval on objects that you have read from another source. The bad guys could easily compromise your system.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.