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

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Fri Jul 21 08:45:11 EDT 2006

On Jul 21, 2006, at 2:54 AM, 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.

If your code might return twice from the use function, isn't it also  
likely that it will continue to use tmp-file from the time it is  
entered (resumed) to the second exit? If so, do you want to use the  
same tmp file or a new one? I doubt your POST thunk knows whether a  
return is the 1st, 2nd, or 3rd. So

(let ((tmp-file '*))
   (lambda () (set! tmp-file (make-temporary-file ...)))
   (lambda () (use tmp-file))
   (lambda () (delete-file tmp-file))))

> Anyway, I was expecting one of PLT's many libraries to include
> something like
> (with-temporary-file body [format-string copy-from-filename  
> directory])

I don't see what the semantics of entering and re-entering body  
should be. Until then, we can't design such a feature.

I am afraid that this is one of those situation where a language can  
provide the building blocks and the programmer must decide what it  

-- Matthias

P.S. I tend to define a with-temp-file myself for the specific  
situation that I am in.

> 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.
> What's your advice?
> -- 
> I shrivel inside each time [Star Wars] is mentioned.
>         -- Sir Alec Guinness
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Posted on the users mailing list.