From: Brian Candler Date: 2011-03-15T07:07:34+09:00 Subject: Re: Splitting up and Reassembling A File Rob P. wrote in post #987385: > Hi, > > I was wondering if you possibly help? > > I am looking to split up a file, say an image file, and then at a later > date reassemble all of the pieces of this split file to recreate the > image. > > I have implemented this so far; > > file = File.open("image.jpg","rb"){|f|f.read} > i = 1 > file.bytes.each_slice(10000) do |slice| > new_file = File.new("file_#{i}.txt", "w+") > new_file.puts(slice.pack('C*'))) > i = i + 1 > end * Try "wb" not "w+" * Use "print" or "write", not "puts" (which adds a newline) * Messing about with bytes and pack might work, but you may as well just read into a string * Close each file after using it - the block form of File.open is the easiest way to make sure of that Something like this (untested): File.open("image.jpg","rb") do |src| i = 1 while chunk = src.read(10000) File.open("file_#{i}.bin","wb") do |new_file| new_file << chunk end i += 1 end end And of course, you can test this part separately using 'cat' at the command line to try to reassemble the chunks into the original file, and 'cmp' to check the results. -- Posted via http://www.ruby-forum.com/.