0

创建文件并向其中填充数据后,在关闭之前,需要读取部分数据并计算校验和。问题是您无法在关闭文件之前读取数据。代码片段如下。

我的问题是如何创建文件,写入数据,读取文件的一部分,然后关闭它?一种可能的解决方案是在写入文件之前使用缓冲区,但如果文件很大,例如 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
4

1 回答 1

1

您遇到的问题是Ruby IO读取文件并跟踪它在文件中的位置。写出数据后,IO 对象的“搜索头”位于文件底部。当你问它下一行时,因为它在底部,你什么也得不到。

如果您将代码更改为包含 a file.rewind,则它可以工作:

#################
# read file fails
# before close
#################
file.rewind  # <--  THIS IS THE ADDED LINE
while line = file.gets
  puts line
end

#rewind方法将“搜索头”设置回文件的开头,这就是您要执行的操作。

于 2012-08-02T12:40:05.620 回答