1)讀取文件java
用with-open-file函數打開文件python
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或者:erroroop
(let ((in (open "d:/test.lisp" :if-does-not-exist :create))) (when in (format t "~A~%" (read-line in)) (close in)))
4)除了上面第1)點之外,也能夠經過下面方式讀取文件全部行:this
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-表達式:spa
假若有txt文件包含如下內容:
code
(hello world)
234
"a string" ;;this is a comment
((a b)
(c d))orm
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
(未完待補。。)
string