2012-03-25 97 views
3

我如何使用Racket创建文件以便能够存储和编辑用户输入的数据,或者例如高分。我已经阅读了一些文档,并没有找到如何做到这一点的明确答案。通过球拍创建文件

回答

5

2htdp/batch-io库中有一些读取和写入文件的简单函数:http://docs.racket-lang.org/teachpack/2htdpbatch-io.html。他们是比较有限的,因为它们只在同一目录下的程序本身访问一个文件,但你可以这样做:

(require 2htdp/batch-io) 
(write-file "highscore.txt" "Alice 25\nBob 40\n") 

将数据写入到一个文件中(\ n表示换行符),然后

(read-lines "highscore.txt") 

找回文件的行,作为字符串列表。

4

Racket Guide有关于输入和输出的章节。举例说明first section解释读写文件。它说

文件:open-output-file函数打开用于写入的文件,并 open-input-file打开文件进行读取。

Examples: 
> (define out (open-output-file "data")) 
> (display "hello" out) 
> (close-output-port out) 
> (define in (open-input-file "data")) 
> (read-line in) 
"hello" 
> (close-input-port in) 

如果文件已经存在,那么通过open-output-file默认 引发一个例外。供应像#:exists 'truncate#:exists 'update 一个选项来重新编写或更新文件:

等。