流(stream)

Common Lisp 的流对象有单向输入、单向输出和双向输出三种。

7 个标准流被称为标准初始流(standard initial streams)。

;;; *query-io*,双向流,一般用于询问用户情况下,用来代替 *standard-input* 和 *standard-output*

;;; peek-char,读取流的下一个字符,但这里不会改变流状态。
(with-open-file (stream #p"test")
  (loop for c = (peek-char nil stream nil)
     while c
       (progn
         (princ c)
         (read-char stream))))

;;; 读取文件内容(字符串返回)
;; 版本 1:
(defun read-file-content (filename)
  "读取指定文件的内容"
  (with-open-file (stream filename)
    (let ((data (make-string (file-length stream))))
      (read-sequence data stream)
      data)))
;; 版本 2:
(defun read-file-content (filename)
  (with-open-file (s filename)
    (with-output-to-string (out)
      (loop for line = (read-line s nil)
         while line
         do (write-string (format nil "~A~%" line) out)))))

;;; 逐行处理文件
(with-open-file (stream #p"/etc/passwd" :direction :input)
  (loop for line = (read-line stream nil)
     while line
     do
       (print line)))