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

From: Jens Axel Søgaard (jensaxel at soegaard.net)
Date: Fri Jul 21 08:57:07 EDT 2006

Eric Hanchrow wrote:

>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 ...)))
>  (dynamic-wind
>      void
>      (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 ...)))
>  (dynamic-wind
>      void
>      (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
>something.
>
Herman has a with-temporary-file in his io package at PLaneT.

<http://planet.plt-scheme.org/300/docs/dherman/io.plt/1/7/doc.txt>

  ;; with-temporary-file
  ;; creates a temporary file and automatically deletes it when finished
  (define-syntax with-temporary-file
    (syntax-rules ()
      [(_ file (args ...) e1 e2 ...)
       (let ([file (make-temporary-file args ...)])
         (dynamic-wind
          void
          (lambda () e1 e2 ...)
          (lambda ()
            (when (file-exists? file)
              (delete-file file)))))]))

-- 
Jens Axel Søgaard




Posted on the users mailing list.