Copying Files

Let’s put the File class to some practical use by writing a simple file backup program. When you run copy_files.rb, you will be asked to choose a directory to copy from (the source directory) and another directory to copy to (the target directory). Assuming both directories exist, the program will then copy all the files from the source directory to the target directory. If the target directory does not exist, it will ask you whether you would like to create it, in which case you should enter Y to accept. I’ve supplied a source directory for you; just enter the name srcdir when prompted. When asked for a target directory, enter targetdir in order to create a subdirectory of that name beneath the current directory.

The program initializes the variable sourcedir with the path of the source directory, and it initializes targetdir with the name of the target directory. This is the code that does the file copying:

copy_files.rb

Dir.foreach( sourcedir ){
    |f|
    filepath = "#{sourcedir}\#{f}"
       if !(File.directory?(filepath) ) then
          if File.exist?("#{targetdir}\#{f}") then
              puts("#{f} already exists in target directory" )
          else
              FileUtils.cp( filepath, targetdir )
              puts("Copying... #{filepath}" )
        end
    end
}

Here I’ve used the foreach method of the Dir class, which passes into a block the filename, f, of each file in the specified directory. I’ll have more to say about the Dir class shortly. The code constructs a qualified path to the file, filepath, by appending the filename to the directory name given by the sourcedir variable. I only want to copy data files but not directories, so I test that filepath is a file and not a directory:

if !(File.directory?(filepath) )

I don’t want this program to copy over files that already exist, so it first checks to see whether a file with the name f already exists in the target directory, targetdir:

if File.exist?("#{targetdir}\#{f}")

Finally, assuming all the specified conditions are met, the source file, filepath, is copied to targetdir:

FileUtils.cp( filepath, targetdir )

Here cp is a file-copy method found in the FileUtils module. This module also contains a number of other useful file-handling routines such as mv(source, target) to move a file from source to target, rm( files ) to delete one or more files listed in the files parameter, and mkdir to create a directory as I have done when creating targetdir in the current program:

FileUtils.mkdir( targetdir )
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.122.82