[Rd] Unix-like touch to update modification timestamp of file?

Henrik Bengtsson hb at stat.berkeley.edu
Wed Feb 27 06:54:32 CET 2008


Hi,

is it possible to update the modification time stamp of a file using R
(on file systems supporting it)?  It is sufficient to update the
modification time to the current time.  The best I can do for now is:

touchFile <- function(pathname, ...) {
  if (!file.exists(pathname))
    stop("No such file: ", pathname);

  info <- file.info(pathname);
  if (info$isdir)
    stop("Cannot change the timestamp of a directory: ", pathname);

  oldTimestamp <- info$mtime;

  con <- NULL;
  on.exit({
    if (!is.null(con))
      close(con);
  });

  # Zero-sized files have to be treated specially
  if (info$size == 0) {
    con <- file(pathname, open="w");
  } else {
    con <- file(pathname, open="r+b");
    seek(con=con, where=0, origin="start", rw="read");
    bfr <- readBin(con=con, what="raw", n=1);
    seek(con=con, where=0, origin="start", rw="write");
    writeBin(con=con, bfr);
  }

  invisible(oldTimestamp);
} # touchFile()


# 1. Create a file
pathname <- tempfile()
cat(file=pathname, "Hello world!")
md5a <- digest::digest(pathname, file=TRUE);

# 2. Current time stamp
print(file.info(pathname)$mtime)
## [1] "2008-02-26 21:41:23 Pacific Standard Time"

# 3. Update time stamp
Sys.sleep(1.2);
touchFile(pathname)
print(file.info(pathname)$mtime)
## [1] "2008-02-26 21:41:24 Pacific Standard Time"

# 4. Verify that the contents did not change
md5b <- digest::digest(pathname, file=TRUE);
stopifnot(identical(md5a, md5b))

/Henrik



More information about the R-devel mailing list