Browse | Submit A New Snippet | Create A Package

 

File Splitter

Type:
Class
Category:
File Management
License:
GNU General Public License
Language:
Ruby
 
Description:
File Splitter: Split a file into a number of smaller pieces

Versions Of This Snippet::

Rory O'Kane
Snippet ID Download Version Date Posted Author Delete
3351.0.12008-01-10 11:19Rory O'Kane
Changes since last version::
Re-indented to two spaces to see the levels more easily
1461.02006-04-17 05:51Saajan N

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :1.0.1

# 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 <filename.ext> <num_of_pieces>
# 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 <filename.ext> <num_of_pieces>"
  puts "Example: ruby file_splitter.rb myfile.txt 10"
else
  FileSplitter.new(ARGV[0], ARGV[1].to_i).split
end
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..