1 打开文件
CL也提供了流的抽象,读取文件的一般方式也是open一个文件,然后在返回的流上,调用read-*函数。
(open "path" &key direction element-type if-not-exist) 根据路径打开一个文件,返回一个流
direction支持选项:input :output :io
if-exist可以控制文件存在时的操作,支持:error,:new-version,:rename,:rename-and-delete,:overwrite,:append
if-does-not-exist用于控制文件不存在时的操作,支持:error,:create,:nil
element-type 用于指定打开方式 如果希望以二进制格式打开,则使用'(unsigned-byte 8)
2 读取文件
(read-* stream eof-err-p eof-value) 读取流,如果err-p为真,则系统出错。如果err-p为假,则返回eof-value
(read-char stream) 从流中读取一个字符
(read-line stream) 从流中读取一行
(read stream) 从流中读取一个S表达式,跳过注释和空格
(read-byte stream) 从二进制流中读取字节
(read-sequence seq stream) 读取并填充seq,返回填充的个数,可以通过:start :end指定填充范围
3 写文件
当以:output方式打开文件后,便可以使用各种write函数输出文件。
(write-char char stream) 向流中写一个字符
(write-line line stream) 向流中写一行并换行
(write-string string stream) 向流中写一串,无换行;使用terpri和fresh-line手工控制换行。
(write-byte byte stream) 向流写一字节
(write-sequence seq stream) 向流写一序列,序列必须是基于char的。
(write obj ... ostream) 输出对象,默认向标准输出写,下同
(print obj ostream) 输出S表达式
(prin1 obj ostream)
(princ obj ostream)
(pprint obj ostream)
4 关闭文件
(close stream) 关闭流
打开关闭文件的操作如此频繁,以至于CL提供了with-open-file来封装open...close的操作。
(with-open-file (variable open-args*) body-form*)
5 路径名抽象
对于字符串表示的文件名,会存在操作系统的移植性问题。因而CL提供了pathname的抽象,可以用结构化的信息表示文件名。pathname有6个元素:host device dirctory name type version;每个元素都接受字符串值。其中目录元素是一个列表,包含:absolute或:relative前端。
(pathname "path") 构造一个路径名对象,其字面表示为#p"..."
(make-pathname :directory :name :type :defaults "path")
以下6个函数,分别访问路径名的各个元素:(pathname-host p)、(pathname-device p)、(pathname-directory pn)、(pathname-name p)、(pathname-type p)、pathname-version p)
以下函数,分别获取路径名各部分的字符串表示
(namestring pn) 获取路径名的字符串表示
(directory-namestring pn) 获取目录的字符串表示
(file-namestring pn) 获取文件的字符串表示
(merge-pathnames path1 path2) 合并为path2/path1,如果path2为是路径
(enough-namestring #p"/root/a/b" #p"/root/a/") 从第一路径中去除第二路径
6 两种表示法
目录可以有两种表示法:文件法和目录法;在文件法中,最后一级目录作为name项存在,而在目录表示法中,所有目录均作为dirctory项存在。
当前make-pathname的实现均表示成文件法,除法路径最后一个字符是路径分隔符。
7 文件系统函数
(probe-file path) 若文件存在,则返回真实路径,否则返回NIL
(directory path) 返回path下文件列表,不同LISP的实现不大一样
(delete-file path) 删除一个文件
(rename-file old new)
(ensure-directory-exist path) 创建目录,path必须是目录形式,以分隔符结束
(file-write-date file) 返回更新时间戳
(file-author path) 返回文件属主
(file-length stream) 返回文件字节数
(file-position stream pos) 返回/或设置流当前位置
8 其他IO类型
make-string-input-stream 创建可供read*的stringstream
make-string-output-stream 创建可供write或print的stringstream,流中数据用get-output-stream-string
with-input-from-string 封装
with-output-to-string 封装
make-broadcast-stream 创建broadcast-stream
make-concatenated-stream
make-two-way-stream
make-echo-stream