我想编写一个函数,该函数以两个文件的名称作为参数,并将内容从第一个文件复制到第二个文件。
到目前为止,我编写了一个从文件读取的函数:
(defun readFile (name)
(let ((in (open name)))
(format t "~a~%" (read-line in))
(close in)))
还有一个将字符串写入文件的函数:
(defun writeFile (name content)
(with-open-file (stream name
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(format stream content)))
按照 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))
)))
现在唯一的问题是它没有读取整个文件。
Common Lisp 食谱实际上包含了您问题的答案:
http://cl-cookbook.sourceforge.net/io.html 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))))))
这应该能够处理文本文件和二进制文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)