从字符串中读取和写入整个文件
以下函数将整个文件读入新字符串并返回:
(defun read-file (infile)
(with-open-file (instream infile :direction :input :if-does-not-exist nil)
(when instream
(let ((string (make-string (file-length instream))))
(read-sequence string instream)
string))))
如果文件不存在,结果是 NIL
。
以下函数将字符串写入文件。关键字参数用于指定文件已存在时要执行的操作(默认情况下会导致错误,允许的值是 with-open-file
宏的值)。
(defun write-file (string outfile &key (action-if-exists :error))
(check-type action-if-exists (member nil :error :new-version :rename :rename-and-delete
:overwrite :append :supersede))
(with-open-file (outstream outfile :direction :output :if-exists action-if-exists)
(write-sequence string outstream)))
在这种情况下,write-sequence
可以用 write-string
代替。