References
Scheme里面的IO是通过一种叫做port的东西来进行输出输入的。而Port可以被绑定到不同的设备上,一般默认情况下就是我们的console。这个port的概念就和C里面的file discriptor的概念一样。
默认情况下,默认的输入port可以通过(current-input-port
)来获得,而输出的可以通过
(current-output-port)
来获取。
Input
输入的procedrue有下面几种
- (read-char) 从port读入一个字符。
- (read-line) 从port读入一行,以'\n'分割。行末的'\n'不包含在结果中。
- (read) 从port读入一个s-expression,如(1 2 +)或者1。
Output
- (write-char char)将char写到默认的port上,char的格式是#\a。
- (write sexp)和(display sexp)都将sexp(s expression)输出
- (newline)输出一个newline
File IO
-
(open-input-file "hello.txt") 返回一个与hello.txt关联的input port。
-
(open-output-file "greeting.txt")
返回一个与greeting.txt关联的output port。 - 上面的port需要在使用完之后关闭,使用下面的procedure来完成。
(close-output-port o) (close-input-port o)
Automatic File IO
- 可以利用下面的procedure来自动管理文件的打开和关闭。
(call-with-input-file "hello.txt" (lambda (i) (let* ((a (read-char i)) (b (read-char i)) (c (read-char i))) (list a b c))))
call-with-input-file接受一个文件名和一个procedure,这个procedure接受这个input file port作为参数。procedure的返回值作为call-with-input-file的参数返回,但是返回前确保了hello.txt已经被关闭。
String Port
可以将一个string关联在一个port上,这样之后的IO操作都作用在string上面。
(open-input-string "hello world")
将"hello world"关联到一个port上,并作为返回值返回。-
(open-output-string)
则打开一个新的output string,之后的string可以通过(get-output-string o)
来进行获取。 - string port没有必要关闭。
Loading File
(load file)将文件读入,并将里面的每个scheme expression进行evaluate。同时也可以在load进来的
文件里面写load表达式,这样可以同时load很多的文件。
但是需要注意的是,load文件的相对路径是相对于scheme解析器的当前路径的,所以如果需要从相对路径load文件的话,需要查看相应的scheme的实现。