Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy the contents of one file to another using Ruby's file methods?

Tags:

ruby

I want to copy the contents of one file to another using Ruby's file methods.

How can I do it using a simple Ruby program using file methods?

like image 835
Mithun Sasidharan Avatar asked Dec 05 '11 11:12

Mithun Sasidharan


2 Answers

There is a very handy method for this - the IO#copy_stream method - see the output of ri copy_stream

Example usage:

File.open('src.txt') do |f|
  f.puts 'Some text'
end

IO.copy_stream('src.txt', 'dest.txt')
like image 132
Marek Příhoda Avatar answered Oct 21 '22 10:10

Marek Příhoda


Here is a simple way of doing that using ruby file operation methods :

source_file, destination_file = ARGV 
script = $0

input = File.open(source_file)  
data_to_copy = input.read()  # gather the data using read() method

puts "The source file is #{data_to_copy.length} bytes long"

output = File.open(destination_file, 'w')
output.write(data_to_copy)  # write up the data using write() method

puts "File has been copied"

output.close()
input.close()

You can also use File.exists? to check if the file exists or not. This would return a boolean true if it does!!

like image 34
Mithun Sasidharan Avatar answered Oct 21 '22 10:10

Mithun Sasidharan