# Splits a file (eg. abc.ext) to a number of smaller files (eg. abc.ext.piece1, abc.ext.piece2 etc) # Does not do any error handling # Expects file to be split to exist in the current directory! # Usage: ruby file_splitter.rb # Example: ruby file_splitter.rb myfile.txt 10 class FileSplitter def initialize(filename, num_of_splits) @filename = filename @file = File.new(filename, "rb") @num_of_splits = num_of_splits # when we are splitting a file into a given number of pieces, the last piece could be bigger than the others @each_size, @extra = File.size(filename).divmod(@num_of_splits) end def split (1..@num_of_splits).each do |n| File.open(@filename + ".piece#{n}", "wb") do |f| f << @file.read(@each_size) if n == @num_of_splits and not @extra.nil? f << @file.read(@extra) end end end end end if ARGV.size != 2 puts "Usage: ruby file_splitter.rb " puts "Example: ruby file_splitter.rb myfile.txt 10" else FileSplitter.new(ARGV[0], ARGV[1].to_i).split end