safe-output.ss
#lang scheme/base

(define (safe-output-file name next)
  (let* ((temp (path-add-suffix name ".tmp")))
    (with-handlers
        ((exn:fail? 
          (λ (e)
            (when (file-exists? temp)
              (delete-file temp)))))
      (call-with-output-file 
          temp
        #:exists 'replace
        (λ (output)
          (next output)
          (when (file-exists? name)
            (delete-file name))
          (rename-file-or-directory temp name))))))
          
(define (test)
  (safe-output-file 
   (build-path (find-system-path 'home-dir) "feep.txt")
   (λ (output)
     (write '(this is a toast) output))))

(provide safe-output-file)