水晶从文件读取x个字节

Ba7*_*chy 2 crystal-lang

我有这个代码:

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

puts b
Run Code Online (Sandbox Code Playgroud)

我希望从/ dev/urandom device\file获取前1024个字节,而不是我得到一个错误,表示read只接受slice而不是Integer.

所以我试着这样做:

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

但后来我在输出中找回了"1000".

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

Jon*_*Haß 8

你所做的并不是很理想,但它确实奏效了.IO#read(Slice(UInt8))返回实际读取的字节数,以防文件小于您请求的数据或由于某些其他原因数据不可用.换句话说,它是部分阅读.所以,你得到1000b,因为你通过片充满了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
Run Code Online (Sandbox Code Playgroud)

IO还提供各种便利功能,用于在各种编码中读取字符串直到特定令牌或达到极限.许多类型还实现了from_io界面,使您可以轻松读取结构化数据.