Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy file contents to another file?

Tags:

file-io

ruby

As basic as this seems, I simply can't manage to copy the contents of one file to another. Here is my code thus far:

#!/usr/bin/ruby

Dir.chdir( "/mnt/Shared/minecraft-server/plugins/Permissions" )

flist = Dir.glob( "*" )

flist.each do |mod|
    mainperms = File::open( "AwesomeVille.yml" )
    if mod == "AwesomeVille.yml"
        puts "Shifting to next item..."
        shift
    else
        File::open( mod, "w" ) do |newperms|
            newperms << mainperms
        end
    end
    puts "Updated #{ mod } with the contents of #{ mainperms }."
end
like image 339
Mark Avatar asked May 14 '11 23:05

Mark


1 Answers

Why copy the contents of one file to another? Why not use either the OS to copy the file, or use Ruby's built-in FileUtils.copy_file?

ri FileUtils.copy_file
FileUtils.copy_file

(from ruby core)
------------------------------------------------------------------------------
  copy_file(src, dest, preserve = false, dereference = true)

------------------------------------------------------------------------------

Copies file contents of src to dest. Both of src and
dest must be a path name.

A more flexible/powerful alternate is to use Ruby's built-in FileUtils.cp:

ri FileUtils.cp
FileUtils.cp

(from ruby core)
------------------------------------------------------------------------------
  cp(src, dest, options = {})

------------------------------------------------------------------------------

Options: preserve noop verbose

Copies a file content src to dest.  If dest is a
directory, copies src to dest/src.

If src is a list of files, then dest must be a directory.

  FileUtils.cp 'eval.c', 'eval.c.org'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
  FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
  FileUtils.cp 'symlink', 'dest'   # copy content, "dest" is not a symlink
like image 116
the Tin Man Avatar answered Oct 05 '22 15:10

the Tin Man