创建2个文件并从Lisp中的另一个文件写入不同的内容

时间:2017-03-12 22:21:04

标签: file io lisp common-lisp

我正在尝试从另一个文件中写入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行并在另一个文件中休息)来写入这些文件。

1 个答案:

答案 0 :(得分:2)

挑剔

  1. 直接使用open / close几乎总是错误的。请改用with-open-file以确保文件已关闭,无论如何。

  2. 比较数字时,请使用=代替equal

  3. 明确指定默认参数(例如:if-does-not-exist :error:direction :input)并不是一个好主意,因为它会增加混乱并降低代码可读性。

  4. (read-line stream) 从不返回nil。它要么返回string,要么发出end-of-stream错误信号。请阅读手册或参阅下面的代码,了解如何正确调用它。

  5. 代码

    (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)))))
    

    必读

    1. read-line
    2. write-line
    3. loop
    4. 作业

      如果source文件包含少于num-lines行,会发生什么?

      期望的行为是什么?

      你会如何修复这个错误?