作为一个基本功能,文件操作对于大多数语言来讲都是必须支持的,Lisp语言和大多数语言一样提供了文件操作接口。
在Lisp中对文件的操作通过函数open来实现,通过open函数打开一个文件,然后通过read函数读取文件内容,或者通过format函数将数据写入文件中。
函数open的第一个参数是目标文件的路径和文件名,然后是一些参数,包括:
:direction用于指定文件打开后会执行的操作,缺省值是读取,如果需要写入的话使用:output作为值
:if-does-not-exist用于指定目标文件不存在时的操作,可以指定值为nil,表示文件不存在时open函数返回nil,也可以指定为:create,表示文件不存在的话就创建一个。
:if-exists用于指定目标文件存在时的操作,可以指定值为:overwrite,表示如果目标文件存在的话直接覆盖原文件。
所以有下面这样的样例代码:
(setq file-to-read (open "c:\\workspace\\lisp\\file-test.txt" :if-does-not-exist nil))
(setq file-to-write (open "c:\\workspace\\lisp\\file-test.txt" :direction :output :if-does-not-exist :create :if-exists :overwrite))
第一行代码使用open函数以读的方式打开文件“c:\\workspace\\lisp\\file-test.txt”,用变量file-to-read指向打开的文件,如果文件不存在则file-to-read的值为nil
第二行代码使用open函数以写的方式打开文件“c:\\workspace\\lisp\\file-test.txt”,用变量file-to-write指向打开的文件,如果文件不存在就创建一个,如果文件存在就覆盖原文件。
以写的方式打开文件后,可以使用format函数将内存中的数据写入文件中,样例如下:
(format file-to-write "~a~%" sample-list)
以上代码将sample-list对象写入文件file-to-write中
以读得方式打开文件后,可以通过read函数读取文件中的内容,样例如下:
(read file-to-read)
以上代码从文件file-to-read中读取一行,并尝试按lisp语法解读该行的内容,如果写进去的是一个列表,读出来的也会是一个列表。
在文件操作完成后记得使用close函数关闭文件,格式如下:
(close 文件变量)
下面是文件读写的一个简单样例:
(defun my-write-file ()
;;文件写入样例
;定义一个列表变量
(setq sample-list '(a b c (1 2) d e f (one two three (right left up down) four) g h i))
;以写的方式打开文件,将文件句柄赋予变量file-to-write
(setq file-to-write (open "c:\\workspace\\lisp\\file-test.txt" :direction :output :if-does-not-exist :create :if-exists :overwrite))
;将变量sample-list写入文件
(format file-to-write "~a~%" sample-list)
;关闭文件
(close file-to-write))
(defun my-read-file ()
;;文件读取样例
;以读的方式打开文件
(setq file-to-read (open "c:\\workspace\\lisp\\file-test.txt" :if-does-not-exist nil))
;如果文件不存在就退出
(if (not file-to-read)
(progn
(format t "file open failed ~%")
(return-from my-read-file nil)))
;读取文件中的一行,将读出来的值赋予list-readed
(setq list-readed (read file-to-read))
;关闭文件
(close file-to-read)
;判断list-readed是不是一个列表,并在控制台输出
(format t "is list-readed is a list:~a ~%" (listp list-readed))
;返回读出来的值
list-readed)