1)读取文件
用with-open-file函数打开文件
CL-USER> (defun my-read-file ()
(with-open-file (stream "d:/test.lisp")
(do ((my-file (read-line stream) (read-line stream nil 'eof)))
((eq my-file 'eof) "Reached end of file")
(format t "~A~%" my-file))))
2)用open、read-line和close读取文件的第一行
CL-USER> (let ((in (open "d:/test.lisp")))
(format t "~A~%" (read-line in))
(close in))
3)打开文件不存在时可以返回nil、:create或者:error
(let ((in (open "d:/test.lisp" :if-does-not-exist :create)))
(when in
(format t "~A~%" (read-line in))
(close in)))
4)除了上面第1)点以外,也可以通过下面方式读取文件所有行:
CL-USER> (let ((in (open "d:/test.lisp" :if-does-not-exist nil)))
(when in
(loop for line = (read-line in nil) ;;遇到文件末尾时返回nil
while line do (format t "~A~%" line))
(close in)))
5)read函数只能读取lisp的四个S-表达式:
假如有txt文件包含以下内容:
(hello world)
234
"a string" ;;this is a comment
((a b)
(c d))
CL-USER> (defparameter *s* (open "d:/test-file.txt"))
*S*
CL-USER> (read *s*)
(HELLO WORLD)
CL-USER> (read *s*)
234
CL-USER> (read *s*)
"a string"
CL-USER> (read *s*)
((A B) (C D))
CL-USER> (close *s*)
T
(未完待补。。)