How do I perform basic file I/O operations Scheme?
Asked Answered
A

3

5

I want basic examples to try basic read/write/update operations on a file. I'm finding it difficult not having appropriate resources to learn from.

Assize answered 15/11, 2010 at 4:19 Comment(0)
B
2

It's mostly implementation-specific. Given that you're using racket, see the guide section and the reference manual.

Bevbevan answered 15/11, 2010 at 4:30 Comment(0)
W
17

The easiest way to read/write files in any R5RS compliant Scheme is:

;; 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 has this notion of ports that represent devices on which I/O operations could be performed. Most implementations of Scheme associate call-with-input-file and call-with-output-file with literal disk files and you can safely use them.

Whoopee answered 15/11, 2010 at 5:42 Comment(0)
F
5

See the following post if you are working with a R5RS compliant Scheme:

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

The solution presented there is as follows:

; 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)
Fotheringhay answered 4/2, 2016 at 2:45 Comment(2)
For reference, MIT Scheme uses (open-output-file "my-file-name.txt" #t). We can use for-each to write more conveniently https://mcmap.net/q/1920721/-reading-and-writing-from-file-in-scheme.Endostosis
Please don't post the same answer to different questions, flag as a duplicate instead.Plath
B
2

It's mostly implementation-specific. Given that you're using racket, see the guide section and the reference manual.

Bevbevan answered 15/11, 2010 at 4:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.