What is the most robust method to move an entire directory from say /tmp/RtmpK4k1Ju/oldname
to /home/jeroen/newname
? The easiest way is file.rename
however this doesn't always work, for example when from
and to
are on different disks. In that case the entire directory needs to be recursively copied.
Here is something I came up with, however it's a bit involved, and I'm not sure it will work cross-platform. Is there a better way?
dir.move <- function(from, to){
stopifnot(!file.exists(to));
if(file.rename(from, to)){
return(TRUE)
}
stopifnot(dir.create(to, recursive=TRUE));
setwd(from)
if(all(file.copy(list.files(all.files=TRUE, include.dirs=TRUE), to, recursive=TRUE))){
#success!
unlink(from, recursive=TRUE);
return(TRUE)
}
#fail!
unlink(to, recursive=TRUE);
stop("Failed to move ", from, " to ", to);
}