Getting a safe path for a temporary file

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jan 17 13:32:08 PST 2015


On Saturday, January 17, 2015 13:47:37 via Digitalmars-d-learn wrote:
> Is it currently possible to get the path to a safe temporary
> file, i.e. one that is guaranteed to be freshly created and will
> not override another existing file?
>
> There's `std.file.tempDir`, which doesn't create a unique file.
> Then there's `std.stdio.tmpfile()`, which does, but it returns a
> `File` object, and its `name` property is `null`.
>
> Did I miss something? IMO this is very import functionality. One
> use case is passing these names as command line arguments to an
> external program that doesn't support stdin/stdout.

The _only_ way to this write is to randomly generate a file name and then
open the file with O_CREAT | O_EXCL (or more likely,
O_RDWR | O_CREAT | O_EXCL), and then retry with a new name if the creation
fails (good enough random name generation would likely require only two
attempts at most). Simply randomly generating a file name is not enough,
because it's still technically possible for the file to already exist (even
if it's unlikely), and even checking for the file's existence prior to
opening it isn't enough, because technically, the file could be created by
another program in the small amount of time between when you checked for the
file's existence and tried to create it.

POSIX actually has mkstemp for doing this for you, but on some operating
systems, it restricts the number of random files that it can generate to as
little as 26 (at least, that's what I recall the number being). I don't
think that any of the POSIX systems that we currently support have an
implementation of mkstemp that's quite that bad, but all in all, I don't
think that using mkstemp is a good idea.

The problem is solved simply enough by randomly generating a file name (e.g.
with rndGen()) and then using the correct flags with open. And I actually
have code that does this that I was working on getting into Phobos, but the
problem was getting access to the correct function on Windows (_wsopen_s, I
believe). It wasn't available in druntime, and I didn't get around to fixing
that (IIRC, because I started looking into the whole problem of how to deal
with windows bindings in druntime in general and going down a rat hole that
I didn't have time for). So, I never finished that pull request, and I
really should get back to it.

But I think that what we need is a function in std.stdio (e.g tempFile
insteaf of tmpfile) which returns an open File with a randomly generated
name and gives you access to its name rather than using C's tmpfile, which
does not give you access to the name and deletes the file on you when it's
closed. IMHO, tmpfile is pretty useless - especially when it comes to unit
tests.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list