Skip to content

Instantly share code, notes, and snippets.

@HenrikBengtsson
Last active May 10, 2016 16:21
Show Gist options
  • Save HenrikBengtsson/a5c1ad9d079c34c25407 to your computer and use it in GitHub Desktop.
Save HenrikBengtsson/a5c1ad9d079c34c25407 to your computer and use it in GitHub Desktop.
Create a temporary file with content on the fly
#' Create a temporary file with content
#'
#' Create a temporary file with content that will auto delete
#' as soon as there is no longer any references to it.
#'
#' @param content A character string to be written to the file
#' @param ... Optional arguments to \code{\link[base]{tempfile}()}.
#'
#' @return The absolute pathname to the temporary file.
#'
#' @examples
#' md5 <- tools::md5sum(tmpfile("Hello world!"))
#'
#' @export
tmpfile <- function(content=NULL, ...) {
pathname <- tempfile(...)
cat(content, file=pathname)
env <- new.env(parent=emptyenv())
env$pathname <- pathname
reg.finalizer(env, function(e) file.remove(e$pathname), onexit=TRUE)
attr(pathname, "gc") <- env
pathname
}
md5 <- tools::md5sum(tmpfile("Hello world!"))
print(md5)
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## Proof that auto delete works
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## Temporary files before
tfiles <- dir(path=tempdir(), full.names=TRUE)
## Create temporary file on the fly without any references to it
bfr <- readLines(tmpfile("Hello world!\n"))
print(bfr)
## Find new temporary file
tfile <- setdiff(dir(path=tempdir(), full.names=TRUE), tfiles)
print(tfile)
stopifnot(file.exists(tfile))
## The on-the-fly temporary file is removed
## whenever the garbage collector runs
gc()
stopifnot(!file.exists(tfile))
@HenrikBengtsson
Copy link
Author

An example of a real-world problem where this will be useful:

cluster.functions <- BatchJobs::makeClusterFunctionsTorque(tmpfile('
## Job name
#PBS -N <%= job.name %>

## Direct streams to our logfile:
#PBS -o <%= log.file %>

## Run R:
Rscript --verbose "<%= rscript %>"
'))

@HenrikBengtsson
Copy link
Author

tmpfile() is in R.utils 2.3.0 (on CRAN) since 2016-04-14.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment