Getting a safe path for a temporary file

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Oct 22 19:17:54 UTC 2017


On Sunday, October 22, 2017 15:21:37 Shriramana Sharma via Digitalmars-d-
learn wrote:
> On Saturday, 17 January 2015 at 17:16:41 UTC, Tobias Pankrath
>
> wrote:
> > You're looking for core.sys.posix.stdlib : mkstemp.
> >
> > I think that should be used by std.stdio.File as well, care to
> > create an enhancement request in bugzilla?
>
> Though this thread is old, I ran into the issue when wanting to
> create a temporary file in my D program and so filed this:
> https://issues.dlang.org/show_bug.cgi?id=17926
>
> For my program right now I'm using a souped-up version using a
> static array:
>
> import std.stdio;
>
> struct TempFile
> {
>      string name;
>      private File handle;
>      alias handle this;
> }
>
> TempFile tempFileOpen()
> {
>      char[20] name = "/tmp/XXXXXX";
>      File handle;
>
>      import core.sys.posix.stdlib: mkstemp;
>      handle.fdopen(mkstemp(name.ptr), "w");
>
>      import std.string: fromStringz;
>      return TempFile(fromStringz(name.ptr).idup, handle);
> }
>
> void main()
> {
>      TempFile tfile;
>      tfile = tempFileOpen();
>      writeln(tfile.name);
>      tfile = tempFileOpen();
>      writeln(tfile.name);
> }

We did have a function for creating a temporary file and returning it as a
File, but it quickly got canned, because adding that functionality to
std.stdio resulted in "hello world" increasing in size, which apparently was
considered unacceptable:

https://issues.dlang.org/show_bug.cgi?id=14599

I did recently create this enhancement request:

https://issues.dlang.org/show_bug.cgi?id=17912

and this PR:

https://github.com/dlang/phobos/pull/5788

It creates a function in std.file that acts similar to std.file.write but
which writes to a randomly generated file name instead of the one you tell
it. So, you don't get an open file out of the deal, but you can write data
to it when it's first opened, and you can reopen it afterwards (which is
usually what I've seen the need for anyway - e.g. a test where you need to
pass a filename to a function that you're testing so that it can open it and
do whatever it does normally).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list