我想编写一个函数,该函数将两个文件的名称作为参数,并将内容从第一个文件复制到第二个文件。
到目前为止,我编写了一个从文件中读取的函数:
(defun readFile (name)
(let ((in (open name)))
(format t "~a~%" (read-line in))
(close in)))
Run Code Online (Sandbox Code Playgroud)
还有一个将字符串写入文件的函数:
(defun writeFile (name content)
(with-open-file (stream name
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(format stream content)))
Run Code Online (Sandbox Code Playgroud)
按照 Savantes 的说明,我再次编写了该函数,它的外观如下:
(defun read-write-to-file (input-file output-file)
(WITH-OPEN-FILE (output-stream output-file
:direction :output
:if-exists :new-version
:if-does-not-exist :create)
(WITH-OPEN-FILE (input-stream input-file
:direction :input)
(FORMAT output-stream "~a" (READ input-stream nil 'eof))
)))
Run Code Online (Sandbox Code Playgroud)
现在唯一的问题是它没有读取整个文件。
小智 5
Common Lisp 食谱实际上包含了您问题的答案:
http://cl-cookbook.sourceforge.net/io.html
请参阅该页面底部的“批量 I/O”部分。
稍加修正和修改后,代码将如下所示:
(defun my-copy-file (from-file to-file)
(with-open-file (input-stream from-file
:direction :input
:element-type '(unsigned-byte 8))
(with-open-file (output-stream to-file
:direction :output
:if-exists :supersede
:if-does-not-exist :create
:element-type '(unsigned-byte 8))
(let ((buf (make-array 4096 :element-type (stream-element-type input-stream))))
(loop for pos = (read-sequence buf input-stream)
while (plusp pos)
do (write-sequence buf output-stream :end pos))))))
Run Code Online (Sandbox Code Playgroud)
这应该能够处理文本文件和二进制文件。