Common Lisp专题3:文件操做

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

相关文章
相关标签/搜索