Crystal 从文件中读取 x 个字节

Crystal reading x bytes from file

我有这个代码:

a = File.open("/dev/urandom")
b = a.read(1024)
a.close

puts b

我希望从 /dev/urandom device\file 中获取前 1024 个字节,但我收到一个错误,它说读取只接受切片而不接受整数。

所以我试着这样做:

b = a.read(("a" * 1000).to_slice)

但后来我在输出中得到了“1000”。

从 Crystal 中的文件读取 x 字节的正确方法是什么?

你做的不是很理想,但确实奏效了。 IO#read(Slice(UInt8)) returns 实际读取的字节数,以防文件小于您请求的文件或由于其他原因数据不可用。换句话说,它是部分读取。所以你在 b 中得到 1000 因为你传递的切片填充了 1000 个字节。有 IO#read_fully(Slice(UInt8)) 阻塞,直到它尽可能多地满足请求,但在任何情况下也不能保证它。

更好的方法如下所示:

File.open("/dev/urandom") do |io|
  buffer = Bytes.new(1000) # Bytes is an alias for Slice(UInt8)
  bytes_read = io.read(buffer)
  # We truncate the slice to what we actually got back,
  # /dev/urandom never blocks, so this isn't needed in this specific
  # case, but good practice in general
  buffer = buffer[0, bytes_read] 
  pp buffer
end

IO 还提供各种便利函数,用于读取字符串,直到特定标记或达到限制,在各种编码中。许多类型还实现了 from_io 接口,使您可以轻松读取结构化数据。