I/O
格式
向屏幕打印数据最常见的方式是使用 format
函数。这类似于 C 中的 printf
,只不过它内嵌了一整套用于打印的语言。
实用 Common Lisp 一书的 这章 包含了许多有用的 format
指令。
文件 I/O
您可以使用 with-open-file
安全地处理文件。
例如,我们可以在您的主目录中打开一个名为 data.txt
的文件,以便写入
(with-open-file (stream (merge-pathnames #p"data.txt"
(user-homedir-pathname))
:direction :output ;; Write to disk
:if-exists :supersede ;; Overwrite the file
:if-does-not-exist :create)
(dotimes (i 100)
;; Write random numbers to the file
(format stream "~3,3f~%" (random 100))))
可以使用 uiop:read-file-string
将文件内容读入一个字符串中
CL-USER> (uiop:read-file-string (merge-pathnames #p"data.txt"
(user-homedir-pathname)))
"44.000
95.000
5.000
97.000
...
15.000"