[plt-scheme] How do I create & use a temp file, ensuring it gets deleted?

From: Eric Hanchrow (offby1 at blarg.net)
Date: Fri Jul 21 02:54:54 EDT 2006

Is there a simple way to create a tempfile, use it, and ensure that it
gets deleted even if the code that uses it raises an error?

I suppose I could do

(let ((tmp-file (make-temporary-file ...)))
      (lambda () (use tmp-file))
      (lambda () (delete-file tmp-file))))

but that seems less than ideal since the middle thunk might
return twice, in which case the last thunk would get called
twice.  Perhaps a simple kludge like

(let ((tmp-file (make-temporary-file ...)))
      (lambda () (use tmp-file))
      (lambda ()
        (when (file-exists? tmp-file)
          (delete-file tmp-file)))))

is all that's needed, but ... that just smells funny.

Anyway, I was expecting one of PLT's many libraries to include
something like

(with-temporary-file body [format-string copy-from-filename directory])

but I didn't find any such thing.  Since what I want seems fairly
basic -- and since I can't think of a really clean and simple way to
write it myself -- I figured I'm overlooking or misunderstanding

What's your advice?
I shrivel inside each time [Star Wars] is mentioned.
        -- Sir Alec Guinness

Posted on the users mailing list.