在Ruby中逐字节读取二进制文件

时间:2016-06-06 20:33:28

标签: ruby parsing

我目前正在尝试以块的形式读取二进制文件,到目前为止我的解决方案是:

first_portion = File.binread(replay_file, 20)
second_portion = File.binread(replay_file, 24, 20)

第一个数字是要读取的字节数,第二个是偏移量。

我知道这很糟糕,因为File.binread每次都会在返回后关闭文件。如何打开文件一次,执行与之相关的操作,然后在完成后关闭它(但仍然使用binread)。

另外,另一个小问题。我已经在python中查看了一些这样的例子并看到了这个:

UINT32 = 'uintle:32'

length = binary_file.read(UINT32)
content = binary_file.read(8 * length)

这究竟是做什么的(它是如何工作的),以及在Ruby中它会是什么样子?

1 个答案:

答案 0 :(得分:3)

您可以使用#read#seek打开文件并读取块中的字节:

File.open(replay_file) do |file|
  first_portion = file.read(20)
  file.seek(24, IO::SEEK_END)
  second_portion = file.read(20)
end

该文件会在end

中自动关闭

关于第二个问题,我不是Python专家,如果我错了,有人会纠正我,但在Ruby中会是这样:

length = binary_file.read(4).unpack('N').first
# 32 bits = 4 bytes
# i.e., read 4 bytes, convert to a 32 bit integer,
# fetch the first element of the array (unpack always returns an array)

content = binary_file.read(8 * length)
# pretty much verbatim

您可以在此处查看更多选项:String#unpack