從字串中讀取和寫入整個檔案

以下函式將整個檔案讀入新字串並返回:

(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 代替。