Last active
September 22, 2017 10:35
-
-
Save NileshN/fddc19f715f75a76ac7dd08a0ccaafe4 to your computer and use it in GitHub Desktop.
File operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
#------------------------------------------------------------------------------------ | |
# Requirement: | |
# Read original file of 35mb, it should write 25mb of data to duplicate file. | |
#------------------------------------------------------------------------------------ | |
original = "/Downloads/all/original.txt" | |
duplicate = "/Downloads/all/duplicate.txt" | |
MEGABYTE = 25 * 1024 | |
file2 = File.open(duplicate, 'a') | |
class File | |
def each_chunk(chunk_size = MEGABYTE) | |
yield read(chunk_size) until eof? | |
end | |
end | |
count = 0 | |
File.open(original, "rb") do |f| | |
f.each_chunk do |chunk| | |
break if count > 970 | |
file2.write("#{chunk}\n") | |
count += 1 | |
end | |
end | |
#------------------------------------------------------------------------------------ | |
# First create a new file 'original.txt' of size 35MB | |
#------------------------------------------------------------------------------------ | |
# one_megabyte = 2 ** 20 # or 1024 * 1024, if you prefer | |
# # Note use 'wb' mode to prevent problems with character encoding | |
# File.open("#{original}", 'wb') do |f| | |
# "35".to_i.times { f.write( SecureRandom.random_bytes( one_megabyte ) ) } | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment