1

I have a textfile in the following folder: C:\myfile.txt

This file is updated once in while. Is it possible to automatically copy the file from C:\myfile.txt to C:\newfolder\myfile.txt every time the file has been updated using R?

If it is not possible in R, do you then know another program that can do it?

Michael
  • 565
  • 4
  • 11
  • By using the task scheduler in windows, you can trigger your R script to copy and paste the file in other direction. [This](https://stackoverflow.com/questions/2793389/scheduling-r-script) may be helpful. – maydin Jun 24 '20 at 12:15

2 Answers2

1

This should work, you can save the script in a .R file and let it run using Rscript :

checktime <- 5 #seconds
lastupdate <- NA
while(T) { 
  if (isTRUE(file.info('test.txt')$ctime!=lastupdate)) {
    lastupdate <- file.info('myfile.txt')$ctime
    cat('New version copy')
    dir.create('./newfolder')
    file.copy('myfile.txt',to = 'newfolder')
    Sys.sleep(checktime)
  }
}

Under Windows, give a name to the script, for example copyscript.R, and just create a .bat file containing Rscript copyscript.R.
You then just need to double click on the .bat file to let it run indefinitely in console mode.

This is perhaps a bit overkill to use R for this task though.

Waldi
  • 39,242
  • 6
  • 30
  • 78
1

You can use R to create a task and save it as a batch as @Waldi suggested. However, there is an easier and less labor-intensive way to solve this problem.

You can use xcopy command of the windows by writing a batch file.

xcopy copies the files or directory when there is a modification in the original source files. See for more details.

Here is an example of how you can run it with a batch file.

Copy, change the paths and paste the following code as an 'automatically copy modified.bat' file and click the batch file. It will open a Command prompt interface (CMD).

Keep the CMD window running, and you can get copies of the files from the source to the destination directory. when the source file is modified, the modified file will be copied to the destination folder.

As long as the command prompt is running, you will get the automatically modified copies to the destination you defined.

@echo off
:loop
REM Execute xcopy every 3 second 
REM to change the second go to timeout 
REM xcopy <Source> [<Destination>]

xcopy "C:\myfile.txt" "C:\newfolder\myfile.txt" /y

timeout /t 3 
goto loop

If you want to run a batch in a silent and hidden way, you should check how to create a task scheduler with a batch file. This website explains some basic steps, you can check it out.

mustafaakben
  • 501
  • 2
  • 5