我正在尝试从另一个文件中写入2个不同的文件内容。程序是我必须在一个文件中写入10行file_a
,其余文件写在另一个文件中。
这是代码:
(defun makeFiles (&optional (nb 1))
(setq file_A
(open "fr_chars.txt"
:direction :input
:if-does-not-exist :error))
(setq file_B
(open "chars_1.txt"
:direction :output
:if-does-not-exist :create
:if-exists :supersede))
(setq file_C
(open "chars_2.txt"
:direction :output
:if-does-not-exist :create
:if-exists :supersede))
(loop
(cond
((equal (read-line file_A) nil) (close file_A) (close file_B) (close file_C) (return 0))
((equal (length (read-line file_B)) 10)
(princ (read-from-string file_A) file_B))
(terpri file_B)
(princ "HERE ARE FR CHARS" file_B)
(princ (read-from-string file_A) file_C)
(terpri file_B)
(terpri file_C)
(setq nb (1+ nb)) ) ) )
拥有file_a
,代码会创建2个文件,但我不会按照所述文件({1}}中的10行并在另一个文件中休息)来写入这些文件。
答案 0 :(得分:2)
直接使用open
/ close
几乎总是错误的。请改用with-open-file
以确保文件已关闭,无论如何。
明确指定默认参数(例如:if-does-not-exist :error
为:direction :input
)并不是一个好主意,因为它会增加混乱并降低代码可读性。
(read-line stream)
从不返回nil
。它要么返回string
,要么发出end-of-stream
错误信号。请阅读手册或参阅下面的代码,了解如何正确调用它。
(defun split-first-lines (source num-lines destination-1 destination-2)
"Read SOURCE, writing the first NUM-LINES to DESTINATION-1
and the rest to DESTINATION-2"
(with-open-file (in source)
(with-open-file (out destination-1 :direction :output)
(loop :repeat num-lines
:do (write-line (read-line in) out)))
(with-open-file (out destination-2 :direction :output)
(loop :for line = (read-line in nil nil) :while line
:do (write-line line out)))))
read-line
write-line
loop
如果source
文件包含少于num-lines
行,会发生什么?
期望的行为是什么?
你会如何修复这个错误?