文件I/O操作 - 方案

6

有人能给我指一些在Scheme中进行基本文件I/O操作的例子吗?

我只是想尝试对文件进行基本的读/写/更新操作。

由于没有合适的学习资源,我发现这很困难。

3个回答

16

在任何符合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-filecall-with-output-file与字面磁盘文件相关联,并且您可以安全地使用它们。


3
如果您正在使用符合R5RS标准的Scheme语言,请参见以下文章: R5RS Scheme输入输出:如何向输出文件写入/追加文本? 解决方案如下:
; 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)

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接