Common Lisp专题3:文件操作

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





(未完待补。。)

转载于:https://my.oschina.net/u/241930/blog/552083

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值