How to prevent file overwriting?

I am looking for a way to prevent R from overwriting files during a session. A more general solution is then better.

Currently, I got a bunch of functions called for example: safe.save , safe.png , safe.write.table , which are implemented more or less like

 safe.smth <- function(..., file) { if (file.exists(file)) stop("File exists!") else smth(..., file=file) } 

It works, but only if I got control over the execution. If some (not mine) function created a file, I cannot stop it from overwriting.

Another way is to set the read-only flag in files that also exceed R due to overwriting existing files. But this also has drawbacks (for example: you do not know which files should be protected).
Or write a single line file:

 protect <- function(p) if (file.exists(p)) stop("File exsits!") else p 

and always use it when providing the file name.

Is there a way to reinforce this behavior in general? Some global connection settings? Maybe only for a subset of functions (graphics devices, file related connections, etc.)? Maybe some kind of system solution?

As a test case, you can use the following:

 test <- function(i) { try(write.table(i, "test_001.csv")) try(writeLines(as.character(i), "test_002.txt")) try({png("test_003.png");plot(i);dev.off()}) try({pdf("test_004.pdf");plot(i);dev.off()}) try(save(i, file="test_005.RData")) try({f<-file("test_006.txt", "w");cat(as.character(i), file=f);close(f)}) } test(1) magic_incantations() # or magic_incantations(test(2)), etc. test(2) # should fail on all writes (to test set read-only to files from first call) 
+5
source share

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


All Articles