Overwrite a directory
overwriteDir(dir, action = c("ask", "overwrite", "append", "no"))
If action
is set to overwrite
, the directory will be
deleted recursively if it exists, a new directory with the same name will be
created, and the function returns TRUE
. If append
is set, the
function creates the directory if necessary and returns TRUE
. If
no
is set, the function does nothing and returns.
If action
is set to ask
, user will be prompted for actions.
If overwrite
is set, the directory will be removed and written anew.
If append
is set, in contrast to overwrite
, the directory and
the files in it are not removed if they exists. In this case, files with the
same name will be overwritten. Otherwise, new directories or files
will be simply created. On the other hand, if the directory does not exist,
it will be created.
If no
is set, no action will be taken. The funciton returns
FALSE
.
createTempDir <- function() {
tmpdir <- tempdir()
tmpfile1 <- tempfile(tmpdir=tmpdir)
tmpfile2 <- tempfile(tmpdir=tmpdir)
writeLines("First file", tmpfile1)
writeLines("Second file", tmpfile2)
return(tmpdir)
}
newTempFile <- function(tmpdir) {
writeLines("Third file", tempfile(tmpdir=tmpdir))
}
if (FALSE) { # \dontrun{
tmpdir <- createTempDir()
overwriteDir(tmpdir, action="ask")
## overwrite: delete the directory and create it a new
tmpdir <- createTempDir()
fileCount <- length(dir(tmpdir))
dir(tmpdir) ## two files should be there
overwriteDir(tmpdir, action="overwrite")
newTempFile(tmpdir)
dir(tmpdir) ## now there should be only one file
stopifnot(length(dir(tmpdir))==1)
## append: append files, and overwrite if a file of the same name is there
overwriteDir(tmpdir, action="append")
newTempFile(tmpdir)
dir(tmpdir) ## a new file is written
stopifnot(length(dir(tmpdir))==2)
## no: no action, and returns FALSE
noRes <- overwriteDir(tmpdir, action="no")
stopifnot(!noRes)
} # }