R5RS Scheme input-output: How to write/append text to an output file?

只谈情不闲聊 提交于 2019-12-20 02:56:14

问题


What is a simple way to output text to file in a R5RS compliant version of Scheme? I use MIT's MEEP (which uses Scheme for scripting) and I want to output text to file. I have found the following other answers on Stackoverflow:

File I/O operations - Scheme

How to append to a file using Scheme

Append string to existing textfile [sic] in IronScheme

But, they weren't exactly what I was looking for.


回答1:


The answers by Charlie Martin, Ben Rudgers, and Vijay Mathew were very helpful, but I would like to give an answer which is simple and easy to understand for new Schemers, like myself :)

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

And, for any lingering questions about the whole "\r\n" thing, please see the following answer:

What is the difference between \r and \n?

Cheers!



来源:https://stackoverflow.com/questions/35191434/r5rs-scheme-input-output-how-to-write-append-text-to-an-output-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!