Append string to existing textfile in IronScheme

一笑奈何 提交于 2019-12-10 18:19:14

问题


We are trying to construct a log file using IronScheme, and we have written a code for it using racket. It works fine in racket, but IronScheme throws an error. This is what we have so far:

(define write-to-log
(lambda(whatToWrite)
(with-output-to-file "robot-log.txt"
(lambda () (printf (string-append whatToWrite "\r\n" ))) #:exists 'append)))

See how we use the "exists" optional parameter when using with-output-to-file. We are not sure how to make this optional parameter work with IronScheme. Are there any ways of getting this to work, or alternative methods?

Please note that we would like to append a string to an existing .txt file. If we don't use the optional argument, an error is thrown saying that the file already exists.


回答1:


IronScheme supports R6RS :)

file-options are not available on with-output-to-file, so you need to use open-file-output-port.

Example (not correct):

(let ((p (open-file-output-port "robot-log.txt" (file-options no-create))))
  (fprintf p "~a\r\n" whatToWrite)
  (close-port p))

Update:

The above will not work. It seems you might have found a bug in IronScheme. It is not clear though from R6RS what file-options should behave like append, if any at all. I will investigate some more and provide feedback.

Update 2:

I have spoken to one of the editors of R6RS, and it does not appear to have a portable way to specify 'append mode'. We, of course have this available in .NET, so I will fix the issue by adding another file-options for appending. I will also think about adding some overloads for the 'simple io' procedures to deal with this as using the above code is rather tedious. Thanks for spotting the issue!

Update 3:

I have addressed the issue. From TFS rev 114008, append has been added to file-options. Also, with-output-to-file, call-with-output-file and open-output-file has an additional optional parameter to indicate 'append-mode'. You can get the latest build from http://build.ironscheme.net/.

Example:

(with-output-to-file "test.txt" (lambda () (displayln "world")) #t)



回答2:


It is my understanding that IronScheme is based on R5RS. From the R5RS Documentation:

for with-output-to-file, the effect is unspecified if the file already exists.

So throwing an error is certainly consistent with the specification and portability of Racket code should not be expected.

Caveat: This code was run on a different R5RS implementation, not IronScheme.

If you just want to append to an existing file in R5RS:

(define my-file (open-output-file "robotlog.txt"))
(display (string-append what-to-write "\r\n") my-file)
(close-output-port my-file)

Is a simple approach that may get you close to what you want.



来源:https://stackoverflow.com/questions/30393528/append-string-to-existing-textfile-in-ironscheme

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