rico_mac rico_mac - 5 years ago 99
Ruby Question

Why won't file contents copy?

I am trying to duplicate the contents of one file to another. Whilst the file is copying, the contents of the files are not. I am not sure where I am going wrong here.

puts "What file do you want to copy?"
print ">"
to_duplicate = STDIN.gets.chomp

puts "what do you want to call the new file?"
print ">"
output_file = STDIN.gets.chomp

puts "copying #{to_duplicate} to #{output_file}."

input = File.open(to_duplicate, 'r') ; prepare_file = input.read

output = File.open(output_file, 'w')

puts "finished duplicating files."

Answer Source

Use FileUtils#cp

The easiest way to copy files is with FileUtils#cp from the Ruby Standard Library. For example:

require 'fileutils'
FileUtils.cp '/tmp/foo', '/tmp/bar'

You can certainly use variables to store filenames collected from standard input if you like. Just don't reinvent the wheel if you don't have to, and leverage the standard libraries whenever you can.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download