From hb at stat.berkeley.edu  Sun Jul 23 02:44:49 2006
From: hb at stat.berkeley.edu (Henrik Bengtsson)
Date: Sat, 22 Jul 2006 17:44:49 -0700
Subject: [Rd] file.copy() of non-existing file creates empty file
Message-ID: <59d7961d0607221744y7da9549dr1f5d0f2a500000f7@mail.gmail.com>

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



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