【问题标题】:R5RS Scheme input-output: How to write/append text to an output file?R5RS 方案输入输出:如何将文本写入/附加到输出文件?
【发布时间】:2016-05-13 11:58:41
【问题描述】:

在 R5RS 兼容版本的 Scheme 中输出文本到文件的简单方法是什么? 我使用麻省理工学院的 MEEP(它使用 Scheme 进行脚本编写)并且我想将文本输出到文件。我在 Stackoverflow 上找到了以下其他答案:

File I/O operations - Scheme

How to append to a file using Scheme

Append string to existing textfile [sic] in IronScheme

但是,它们并不是我想要的。

【问题讨论】:

    标签: io scheme read-write r5rs meep


    【解决方案1】:

    Charlie Martin、Ben Rudgers 和 Vijay Mathew 的回答非常有帮助,但我想给出一个简单易懂的答案,让像我这样的新计划者容易理解 :)

    ; 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)
    

    而且,对于整个 "\r\n" 事情的任何挥之不去的问题,请参阅以下答案:

    What is the difference between \r and \n?

    干杯!

    【讨论】:

    • 你测试过这个吗?我相信您的显示语句中缺少括号。只要我们在这里。为什么不定义文本以包含换行符?
    • 感谢您对括号的提醒。我写这段代码的时候在另一台机器上,所以我错过了。关于“\n”,当然可以放入文本字​​符串,但是如果您尝试附加函数的输出,这会更清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多