Source Edit

This module creates temporary files and directories.

Experimental API, subject to change.

Imports

os, random, winlean

Procs

  1. proc createTempDir(prefix, suffix: string; dir = ""): string {.
  2. ...raises: [OSError, IOError],
  3. tags: [ReadEnvEffect, ReadIOEffect, WriteDirEffect, ReadDirEffect],
  4. forbids: [].}

Creates a new temporary directory in the directory dir.

This generates a dir name using genTempPath(prefix, suffix, dir), creates the directory and returns it, possibly after retrying to ensure it doesn’t already exist.

If failing to create a temporary directory, OSError will be raised.

Note: It is the caller’s responsibility to remove the directory when no longer needed.

Note: dir must exist (empty dir will resolve to getTempDir).

Example:

  1. import std/os
  2. doAssertRaises(OSError): discard createTempDir("", "", "nonexistent")
  3. let dir = createTempDir("tmpprefix_", "_end")
  4. # dir looks like: getTempDir() / "tmpprefix_YEl9VuVj_end"
  5. assert dirExists(dir)
  6. removeDir(dir)

Source Edit

  1. proc createTempFile(prefix, suffix: string; dir = ""): tuple[cfile: File,
  2. path: string] {....raises: [OSError], tags: [ReadEnvEffect, ReadIOEffect],
  3. forbids: [].}

Creates a new temporary file in the directory dir.

This generates a path name using genTempPath(prefix, suffix, dir) and returns a file handle to an open file and the path of that file, possibly after retrying to ensure it doesn’t already exist.

If failing to create a temporary file, OSError will be raised.

Note: It is the caller’s responsibility to close result.cfile and remove result.file when no longer needed.

Note: dir must exist (empty dir will resolve to getTempDir).

Example:

  1. import std/os
  2. doAssertRaises(OSError): discard createTempFile("", "", "nonexistent")
  3. let (cfile, path) = createTempFile("tmpprefix_", "_end.tmp")
  4. # path looks like: getTempDir() / "tmpprefix_FDCIRZA0_end.tmp"
  5. cfile.write "foo"
  6. cfile.setFilePos 0
  7. assert readAll(cfile) == "foo"
  8. close cfile
  9. assert readFile(path) == "foo"
  10. removeFile(path)

Source Edit

  1. proc genTempPath(prefix, suffix: string; dir = ""): string {....raises: [],
  2. tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}

Generates a path name in dir.

The path begins with prefix and ends with suffix.

Note: dir must exist (empty dir will resolve to getTempDir).

Source Edit