IO Streams
License
Boost License 1.0.
Authors
Jason White

@trusted T  tempDir(T = string)() if (is(T : string) || is(T : wstring));

Returns the path to a directory for temporary files.

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.

The return value of the function is cached, so the procedures described above 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.


struct  TempFile(File, Path);

Struct representing a temporary file. Returned by tempFile.


File  file;

The opened  file stream. If AutoDelete.yes is specified, when this is closed, the  file is deleted.


Path  path;

Path to the file. This is not guaranteed to exist if AutoDelete.yes is specified. For example, on POSIX, the file is deleted as soon as it is created such that, when the last file descriptor to it is closed, the file is deleted. If AutoDelete.no is specified, this  path is guaranteed to exist.


enum  AutoDelete: int;

Used with tempFile to choose if a temporary file should be deleted automatically when it is closed.


TempFile!(F, string)  tempFile(F = File)(AutoDelete autoDelete = AutoDelete.yes, string dir = tempDir);

Creates a temporary file. The file is automatically deleted when it is no longer referenced. The temporary file is always opened with both read and write access.

Parameters
AutoDelete autoDelete If set to AutoDelete.yes (the default), the file is deleted from the file system after the file handle is closed. Otherwise, the file must be deleted manually.
string dir Directory to create the temporary file in. By default, this is tempDir.
Example:
Creates a temporary file and writes to it.
auto f = tempFile.file;
assert(f.position == 0);
f.write("Hello");
assert(f.position == 5);
Example:
Creates a temporary file, but doesn't delete it. This is useful to ensure a uniquely named file exists so that it can be written to by another process.
auto path = tempFile(AutoDelete.no).path;