
Last chance! 50% off unlimited learning
Sale ends in
## S3 method for class 'default':
createFileAtomically(filename, path=NULL, FUN, ..., skip=FALSE, overwrite=FALSE, backup=TRUE, verbose=FALSE)
function
that creates and writes to the pathname that
is passed as the first argument. This pathname is guaranteed
to be a non-existing temporary pathname.pushTemporaryFile
()
and popTemporaryFile
().TRUE
and a file with the same pathname already exists,
nothing is done/written.TRUE
and a file with the same pathname
already exists, the existing file is overwritten.
This is also done atomically such that if the new file was not
successfully created,TRUE
and a file with the same pathname already exists,
then it is backed up while creating the new file. If the new file
was not successfully created, the original file is restorepushTemporaryFile
() and popTemporaryFile
() are used for
working toward a temporary file, and
pushBackupFile
() and popBackupFile
() are used for backing up
and restoring already existing file.# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Create a file atomically
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
n <- 10;
createFileAtomically("foobar.txt", FUN=function(pathname) {
cat(file=pathname, "This file was created atomically.
");
cat(file=pathname, "Timestamp: ", as.character(Sys.time()), "", sep="");
for (kk in 1:n) {
cat(file=pathname, kk, "", append=TRUE);
Sys.sleep(0.1);
}
cat(file=pathname, "END OF FILE
", append=TRUE);
}, overwrite=TRUE)
bfr <- readLines("foobar.txt");
cat(bfr, sep="");
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Overwrite the file atomically (emulate write failure)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
tryCatch({
createFileAtomically("foobar.txt", FUN=function(pathname) {
cat(file=pathname, "Trying to create a new file.
");
cat(file=pathname, "Writing a bit, but then an error...
", append=TRUE);
# Emulate write error
stop("An error occured while writing to the new file.");
cat(file=pathname, "END OF FILE
", append=TRUE);
}, overwrite=TRUE)
}, error = function(ex) {
print(ex$message);
})
# The original file was never overwritten
bfr2 <- readLines("foobar.txt");
cat(bfr2, sep="");
stopifnot(identical(bfr2, bfr));
# The partially temporary file remains
stopifnot(isFile("foobar.txt.tmp"));
bfr3 <- readLines("foobar.txt.tmp");
cat(bfr3, sep="");
file.remove("foobar.txt.tmp");
Run the code above in your browser using DataLab