有人能给我指一些在Scheme中进行基本文件I/O操作的例子吗?
我只是想尝试对文件进行基本的读/写/更新操作。
由于没有合适的学习资源,我发现这很困难。
在任何符合R5RS标准的Scheme中,最简单的读写文件方式是:
;; 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
与字面磁盘文件相关联,并且您可以安全地使用它们。
; 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)