Reliable cross-platform directory moving method

What is the most reliable method for moving an entire directory from /tmp/RtmpK4k1Ju/oldname to /home/jeroen/newname ? The easiest way is file.rename , however this does not always work, for example, when from and to are on different drives. In this case, the entire directory must be recursively copied.

This is what I came up with, but it is a bit connected, and I'm not sure that 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); } 
+6
source share
2 answers

I think file.copy would be sufficient.

 file.copy(from, to, overwrite = recursive, recursive = FALSE, copy.mode = TRUE) 

From ?file.copy :

 from, to: character vectors, containing file names or paths. For 'file.copy' and 'file.symlink' 'to' can alternatively be the path to a single existing directory. 

and

 recursive: logical. If 'to' is a directory, should directories in 'from' be copied (and their contents)? (Like 'cp -R' on POSIX OSes.) 

From the description of recursive we know that from can have directories. Therefore, the above code lists all the files before copying. And just remember that the to directory would be the parent of the copied from . For example, after file.copy("dir_a/", "new_dir/", recursive = T) , new_dir will be dir_a .

Your code very much deleted the deletion part. unlink has a nice recursive parameter that file.remove does not support.

 unlink(x, recursive = FALSE, force = FALSE) 
+3
source

Why not just call the system directly:

 > system('mv /tmp/RtmpK4k1Ju/oldname /home/jeroen/newname') 
0
source

Source: https://habr.com/ru/post/950421/


All Articles