Scheme里面的IO

References

  1. http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-9.html#node_chap_7

Scheme里面的IO是通过一种叫做port的东西来进行输出输入的。而Port可以被绑定到不同的设备上,一般默认情况下就是我们的console。这个port的概念就和C里面的file discriptor的概念一样。

默认情况下,默认的输入port可以通过(current-input-port)来获得,而输出的可以通过

(current-output-port)
来获取。

Input

输入的procedrue有下面几种

  1. (read-char) 从port读入一个字符。
  2. (read-line) 从port读入一行,以'\n'分割。行末的'\n'不包含在结果中。
  3. (read) 从port读入一个s-expression,如(1 2 +)或者1。

Output

  1. (write-char char)将char写到默认的port上,char的格式是#\a。
  2. (write sexp)和(display sexp)都将sexp(s expression)输出
  3. (newline)输出一个newline

File IO

  1. (open-input-file "hello.txt")
    返回一个与hello.txt关联的input port。
  2. (open-output-file "greeting.txt")
    返回一个与greeting.txt关联的output port。
  3. 上面的port需要在使用完之后关闭,使用下面的procedure来完成。
    (close-output-port o)
    (close-input-port o)

Automatic File IO

  1. 可以利用下面的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上面。

  1. (open-input-string "hello world")
    将"hello world"关联到一个port上,并作为返回值返回。
  2. (open-output-string)
    则打开一个新的output string,之后的string可以通过
    (get-output-string o)
    来进行获取。
  3. string port没有必要关闭。

Loading File

(load file)将文件读入,并将里面的每个scheme expression进行evaluate。同时也可以在load进来的文件里面写load表达式,这样可以同时load很多的文件。

但是需要注意的是,load文件的相对路径是相对于scheme解析器的当前路径的,所以如果需要从相对路径load文件的话,需要查看相应的scheme的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值