Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File I/O operations - scheme

Tags:

io

scheme

racket

Can someone point me to basic file I/O operations examples in Scheme?

I just want to try basic read/write/update operations on a file.

Finding it difficult as not having appropriate resources to learn from.

like image 695
JJunior Avatar asked Nov 15 '10 04:11

JJunior


1 Answers

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.

like image 171
Vijay Mathew Avatar answered Sep 24 '22 19:09

Vijay Mathew