Last active
May 10, 2016 16:21
-
-
Save HenrikBengtsson/a5c1ad9d079c34c25407 to your computer and use it in GitHub Desktop.
Create a temporary file with content on the fly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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)) | |
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
An example of a real-world problem where this will be useful: