After creating a file and populating data into it, before close, need read part data and
calculate the checksum. The issue is you cant read the data before close the file. Code
snippet is as follows.
My question is how to create a file, write data, read part of the file, then close it? One
possible solution is using a buffer before write to the file, but it is not convenient if
the file is big, such as MB, GB, TB, PB.
begin
File.open(@f_name,"w+") do |file|
@f_old_size.times do
file.write "1"
end
file.flush
file.sync
#################
# read file fails
# before close
#################
while line = file.gets
puts line
end
end
rescue => err
puts "Exception: #{err}"
end
#####################
# read file successfully
# after close it
#####################
File.open(@f_name,"r") do |file|
line = file.gets
puts line
end
The problem that you’re running into is that Ruby IO reads through the file and keeps track of where in the file it is. After you’ve written out your data, the ‘seek head’ of the IO object is at the bottom of the file. When you ask it for the next line, because it’s at the bottom, you don’t get anything.
If you change your code to include a
file.rewindas such, it works:The
#rewindmethod sets the ‘seek head’ back to the beginning of the file, which is what you’re looking to do.