View source code
Display the source code in std/file.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.file.tempDir

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.
  2. The directory given by the TEMP environment variable.
  3. The directory given by the TMP environment variable.
  4. /tmp/
  5. /var/tmp/
  6. /usr/tmp/

string tempDir() @trusted;

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.
  2. The directory given by the TEMP environment variable.
  3. The directory given by the TMP environment variable.
  4. /tmp
  5. /var/tmp
  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

Example

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
writeln(myFile.readText); // "hello"

Authors

Walter Bright, Andrei Alexandrescu, Jonathan M Davis

License

Boost License 1.0.