Question

I have made a simple program to write text to existing files:

;; write to an existing file

(define write-to-a-file
  (lambda (path txt)
    (call-with-output-file path
      (lambda (output-port)
        (write txt output-port)))))

But I want to modify it so that, if the file does not exist, it should be created. If the file exists, then the it should write to the file without deleting previous content of the file. I'm writing in chicken scheme. Any ideas?

Was it helpful?

Solution

Try this for Chicken Scheme:

(define (write-to-a-file path txt)
  (call-with-output-file path
    (lambda (output-port)
      (write txt output-port))
    #:append))

Or this for Racket:

(define (write-to-a-file path txt)
  (call-with-output-file path
    (lambda (output-port)
      (write txt output-port))
    #:exists 'append))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top