temporary files - what is the resolution?

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 25 19:24:21 PDT 2012


On Thursday, July 26, 2012 03:49:27 Marco Leise wrote:
> The question is: Is the problem solved with the fixed bug, or is there
> interest in D functions for temporary files?

Of course there is. tmpfile is a horrible function. And actually, pretty much 
every C function for creating a temp file or even just a temp file name sucks. 
Most of them are marked as "don't ever use" and the like, and the ones that 
aren't are still quite poor (e.g. on some systems tmpnam, can only generate 26 
unique file names with a given prefix). As bad as tmpfile is, at least it _sort 
of_ works. But it doesn't give you a file name, and it deletes the file when 
it's closed, both which make it unusable for a lot of use cases.

I was working on a solution but ran into problems on Windows due to missing C 
function declarations which were required in order to be able to create a 
temporary file without introducing a race condition, and I temporarily tabled 
it. I need to get back to it.

I did create a nice, cross-platform function for generating a random file name 
which used D's random number generators and created a pull request for it ( 
https://github.com/D-Programming-Language/phobos/pull/691 ). By default, It 
puts the file in the directory returned by std.file.tempDir, but you can give it 
a different directory if you want to.

But there's technically a race condition if you check for the file's existence 
and then create it if it didn't exist (and generate a new name if it did, 
check that one for existence, etc.). So, doing

auto file = File(std.file.tempFile());

would have technically had the potential to cause problems (though the file 
name had enough random characters in it to be as good or better than a UUID 
for uniqueness, so practically speaking, it was probably okay even if it was 
theoretically a problem). So, it wasn't merged. If we're going to add 
something, it will be a function which creates a file with a random name but 
which doesn't expose the function for generating the random name.

I intend to create std.stdio.File.tempFile to replace std.stdio.File.tmpfile. 
It will create a temporary file using a name generated with the implementation 
that I put together for generating a random file name and put it in the 
directory returned by std.file.tempDir (or wherever you tell it), and the File 
that it returns will be like any other File save for the fact that it 
generated the name for you. So, it won't get deleted on you or anything 
annoying like that.

I have a fully working implementation on Linux. I just need to sort out the 
Windows C function declaration problem before I can create a pull request for 
it. I expect that it'll be in 2.061.

- Jonathan M Davis


More information about the Digitalmars-d mailing list