【问题标题】:Stop reading from file when it can't read anymore using BinData当文件无法再使用 BinData 读取时停止读取
【发布时间】:2016-06-09 18:34:04
【问题描述】:

目前我正在使用BinData gem 来解析二进制文件格式。它工作得很好,除了我不知道在哪里停下来。该文件分为我使用 BinData Records 读取的属性。可以有 16 到 18 个属性(取决于它所采用的文件)。所以,如果我这样做:

16.times{
    # parse data from property.
}

当有 16 个属性时效果很好,但是,如果我将其增加到 17 个,我会收到以下错误。

'readbytes': End of file reached (EOFError)

我的问题是,我怎样才能避免 16 次一起读取并读取它,直到它读取它可以读取的所有属性,然后在它到达文件结尾错误时停止。

【问题讨论】:

  • 能不能把文件当成数组用read_until: :eof
  • 我想我问这个问题有点过早。在查看文件后,它看起来好像以字符串终止符结尾。我可以寻找并停止阅读。再次感谢您的帮助!
  • 当询问您的代码问题时,我们希望您的代码的最小示例能够证明问题。请阅读“minimal reproducible example”。

标签: ruby bindata


【解决方案1】:

来自examples/tcp_ip.rb

  class PcapFile < BinData::Record
    endian :little

    struct :head do
      uint32 :magic
      uint16 :major
      uint16 :minor
      int32  :this_zone
      uint32 :sig_figs
      uint32 :snaplen
      uint32 :linktype
    end

    array :records, :read_until => :eof do
      uint32 :ts_sec
      uint32 :ts_usec
      uint32 :incl_len
      uint32 :orig_len
      string :data, :length => :incl_len
    end
  end

该示例中采用的方法是告诉 BinData 有一个记录数组,然后让它们全部读取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2011-05-23
    • 2020-04-09
    • 2022-01-25
    • 2021-12-30
    相关资源
    最近更新 更多