ID EN
I/O & Files

tempfile

R Base 3.6.2

tempfile returns a vector of character strings which can be used as names for temporary files.

Syntax

R
<!-- % ../R/temp.R -->
tempfile(pattern = "file", tmpdir = tempdir(), fileext = "")
tempdir(check = FALSE)

Arguments

Parameter Description
pattern a non-empty character vector giving the initial part of the name.
tmpdir a non-empty character vector giving the directory name
fileext a non-empty character vector giving the file extension
check logical indicating if tmpdir() should be checked and recreated if no longer valid.

Return Value

For tempfile a character vector giving the names of possible (temporary) files. Note that no files are generated by tempfile. For tempdir, the path of the per-session temporary directory. On Windows, both will use a backslash as the path separator. On a Unix-alike, the value will be an absolute path (unless tmpdir is set to a relative path), but it need not be canonical (see normalizePath) and on macOS it often is not.

Details

The length of the result is the maximum of the lengths of the three arguments; values of shorter arguments are recycled. The names are very likely to be unique among calls to tempfile in an R session and across simultaneous R sessions (unless tmpdir is specified). The filenames are guaranteed not to be currently in use. The file name is made by concatenating the path given by tmpdir, the pattern string, a random string in hex and a suffix of fileext. By default, tmpdir will be the directory given by tempdir(). This will be a subdirectory of the per-session temporary directory found by the following rule when the R session is started. The environment variables TMPDIR, TMP and TEMP are checked in turn and the first found which points to a writable directory is used: if none succeeds /tmp is

Examples

Example
R
# NOT RUN {
tempfile(c("ab", "a b c"))   # give file name with spaces in!

tempfile("plot", fileext = c(".ps", ".pdf"))

tempdir() # works on all platforms with a platform-dependent result
# }
# NOT RUN {
## Show how 'check' is working on some platforms:
if(exists("I'm brave") && `I'm brave` &&
   identical(.Platform$OS.type, "unix") && grepl("^/tmp/", tempdir())) {
  cat("Current tempdir(): ", tempdir(), "\n")
  cat("Removing it :", file.remove(tempdir()),
      "; dir.exists(tempdir()):", dir.exists(tempdir()), "\n")
  cat("and now  tempdir(check = TRUE) :", tempdir(check = TRUE),"\n")
}

# }

See Also

unlink for deleting files.