Reputation: 41
I am trying to write in 2 different files content from another file. Procedure is that I have to write 10 lines of file_a
in one file and the rest in the another file.
here is the code:
(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)) ) ) )
Having the file_a
, the code creates the 2 files but I don't arrive to write in those files as said (10 lines in file_a
and rest in the another).
Upvotes: 1
Views: 109
Reputation: 60004
Using open
/close
directly is almost always wrong. Use with-open-file
instead to ensure that the file is closed no matter what.
It is not a good idea to specify default argument explicitly (e.g., :if-does-not-exist :error
for :direction :input
) because it increases clutter and reduces code readability.
(read-line stream)
never returns nil
. It either returns a string
, or signals an the end-of-stream
error. Please read the manual or see my code below on how to call it properly.
(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)))))
What would happen if the source
file contains fewer than num-lines
lines?
What is the desired behavior?
How would you fix the bug?
Upvotes: 3