有人能指出我在Scheme中的基本文件I / O操作示例吗?
我只想尝试对文件进行基本的读/写/更新操作。
由于没有适当的资源可供学习,因此很难找到。
答案 0 :(得分:15)
在任何符合R5RS的方案中读取/写入文件的最简单方法是:
;; Read a text file
(call-with-input-file "a.txt"
(lambda (input-port)
(let loop ((x (read-char input-port)))
(if (not (eof-object? x))
(begin
(display x)
(loop (read-char input-port)))))))
;; Write to a text file
(call-with-output-file "b.txt"
(lambda (output-port)
(display "hello, world" output-port))) ;; or (write "hello, world" output-port)
Scheme具有 ports 的概念,表示可以在其上执行I / O操作的设备。 Scheme的大多数实现都将call-with-input-file
和call-with-output-file
与文字磁盘文件相关联,您可以安全地使用它们。
答案 1 :(得分:2)
这主要是针对具体实施的。鉴于您使用的是球拍,请参阅guide section和the reference manual。
答案 2 :(得分:2)
如果您正在使用符合R5RS的计划,请参阅以下帖子:
R5RS Scheme input-output: How to write/append text to an output file?
提出的解决方案如下:
; This call opens a file in the append mode (it will create a file if it doesn't exist)
(define my-file (open-file "my-file-name.txt" "a"))
; You save text to a variable
(define my-text-var1 "This is some text I want in a file")
(define my-text-var2 "This is some more text I want in a file")
; You can output these variables or just text to the file above specified
; You use string-append to tie that text and a new line character together.
(display (string-append my-text-var1 "\r\n" my-file))
(display (string-append my-text-var2 "\r\n" my-file))
(display (string-append "This is some other text I want in the file" "\r\n" my-file))
; Be sure to close the file, or your file will not be updated.
(close-output-port my-file)