如何使用 Common Lisp 成功重写将元素附加到列表的文件?
How can I succesfully re-write a file appending an element to a list using Common Lisp?
我想在 .lisp
文件中写一个 Common Lisp 列表。如果该文件不存在,将创建它并添加元素。
如果文件已经存在,它将重新写入文件,将新内容添加到列表中。
此实现部分有效:
(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)))
如果我这样做:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 4)
有效。该代码创建文件并将 4
作为 '(4)
放入其中。但是,如果我 运行 使用刚刚创建的文件的新元素再次编写代码:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 5)
它抛出一个错误:
Error opening #P"/home/pedro/miscellaneous/misc/tests-output/CL.lisp"
[Condition of type SB-EXT:FILE-EXISTS]
我期待:'(4 5)
我需要改变什么?
创建文件可能是个好主意。否则无法覆盖。
... :if-does-not-exist :create :if-exists :overwrite ...
我想在 .lisp
文件中写一个 Common Lisp 列表。如果该文件不存在,将创建它并添加元素。
如果文件已经存在,它将重新写入文件,将新内容添加到列表中。
此实现部分有效:
(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)))
如果我这样做:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 4)
有效。该代码创建文件并将 4
作为 '(4)
放入其中。但是,如果我 运行 使用刚刚创建的文件的新元素再次编写代码:
(append-to-list-in-file "/home/pedro/miscellaneous/misc/tests-output/CL.lisp" 5)
它抛出一个错误:
Error opening #P"/home/pedro/miscellaneous/misc/tests-output/CL.lisp" [Condition of type SB-EXT:FILE-EXISTS]
我期待:'(4 5)
我需要改变什么?
创建文件可能是个好主意。否则无法覆盖。
... :if-does-not-exist :create :if-exists :overwrite ...