[Rd] file.copy() of non-existing file creates empty file

Henrik Bengtsson hb at stat.berkeley.edu
Sun Jul 23 02:44:49 CEST 2006


Copying a non-existing file using file.copy() creates empty file.  Example:

> file.exists("non-existing-file")
[1] FALSE
> file.copy("non-existing-file", "new-file")
> file.exits("new-file")
[1] TRUE
> file.info("new-file")$size
[1] 0

The reason for this is that file.copy() calls file.create() without
checking if the 'from' file exists;

> file.copy
function (from, to, overwrite = FALSE)
{
    if (!(nf <- length(from)))
        stop("no files to copy from")
    if (!(nt <- length(to)))
        stop("no files to copy to")
    if (nt == 1 && file.exists(to) && file.info(to)$isdir)
        to <- file.path(to, basename(from))
    else if (nf > nt)
        stop("more 'from' files than 'to' files")
    if (nt > nf)
        from <- rep(from, length.out = nt)
    if (!overwrite)
        okay <- !file.exists(to)
    else okay <- rep.int(TRUE, length(to))
    if (any(from[okay] %in% to[okay]))
        stop("file can not be copied both 'from' and 'to'")
    if (any(okay)) {
        okay[okay] <- file.create(to[okay])
        if (any(okay))
            okay[okay] <- file.append(to[okay], from[okay])
    }
    okay
}
<environment: namespace:base>

Adding one line:

    okay <- okay & file.exists(from);

before the last if-statement will do.

/Henrik



More information about the R-devel mailing list