Question

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')
output.write(prepare_file)

puts "finished duplicating files."
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top