#' Create a temporary file securely
#' @description Creates a temporary file securely with a system call to mktemp. A version of mktemp from GNU coreutils or BSD is required.
#' @param template the template, which must end with at least 3 'X's. Only alphanumeric characters, underscore and dots are allowed.
#' @param tmpdir the containing temporary folder. Only alphanumeric characters, underscore and dots are allowed.
#' @return the newly created file name
#' @details
#' R's \code{\link{tempfile}} function makes no guarantee against race conditions, where the same temp file could be generated by different R processes. This is a problem especially 26 *in parallel environments. By contrast, file names generated by \code{mktemp} are guaranteed to be unique.
#'
#' Note that the file is created before the function returns and must be removed manually afterwards.
#' @examples
#' tmpfile <- mktemp()
#' file.remove(tmpfile)
#' @export
mktemp <- function(template = "file.XXXXXXXXXX", tmpdir = tempdir()) {
if (length(template) > 1) {
stop("Expected a single 'template'")
}
if (length(tmpdir) > 1) {
stop("Expected a single 'tmpdir'")
}
if (grepl("[^a-zA-Z0-9.]", template)) {
stop("Only alphanumeric characters, underscore and dots are allowed in 'template'")
}
if (!grepl("XXX$", template)) {
stop("'template' must end with at least 3 'X's")
}
if (grepl("[^a-zA-Z0-9._/]", tmpdir)) {
stop("Only alphanumeric characters, underscore and dots are allowed in the components of 'tmpdir'")
}
fn <- system2("mktemp", file.path(tmpdir, template), stdout = TRUE)
return(fn)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.