Reputation: 2681
I want to write a Common Lisp list in a .lisp
file. If the file does not exist, it will be created and add the element.
If the file already exists, it will re-write the file appending new content to the list.
This implementation partially works:
(defun append-to-list-in-file (filename new-item &aux contents) ;;;;
(setq contents (list)) ;; default in case reading fails
(ignore-errors
(with-open-file (str filename :direction :input)
(setq contents (read str))))
(setq contents (nconc contents (list new-item)))
(with-open-file (str filename :direction :output :if-exists :overwrite)
(write contents :stream str)))
If I do:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 4)
It works. The code creates the file AND puts 4
inside of it as '(4)
. However, if I run the code again with a new element using the file that was just created:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 5)
It throws an error:
Error opening #P"/home/pedro/miscellaneous/misc/tests-output/CL.lisp" [Condition of type SB-EXT:FILE-EXISTS]
I was expecting: '(4 5)
What do I need to change?
Upvotes: 0
Views: 121
Reputation: 139251
Probably a good idea to create the file. Otherwise you can't overwrite it.
... :if-does-not-exist :create :if-exists :overwrite ...
Upvotes: 2