我正在学习ruby,我想以字节方式读取文件。 它可以在短文本文件中正常工作,但是当我用图像或pdf文件尝试它时,它会停止读取字节。
我尝试了不同的实现,但我得到了相同的结果。这是我的代码:
destination = File("file2", "w")
source = File.open("file1", "r")
source.each_byte do |byte|
destination.print (byte).chr
end
destination.close
我也试过了:
destination = File("file2", "w")
source = File.open("file1", "r")
source.each_byte do |byte|
destination.putc(byte)
end
destination.close
我看到0x0D
和0x0A
与\r
和\n
对应。
当我在irb
中手动测试代码时,我看到4个初始元素读取正常,然后忽略第5个(0x0D
= \r
)元素,然后获取下一个元素(0x0A
= \n
)。
当我source.read(1)
时,我会得到正确的值\r
和\n
。
为什么.getbyte
会忽略0x0D
字节(\r
),并说没有更多字节?
我可以从"\r"
和"\n"
字符串中获取小数值吗?
答案 0 :(得分:1)
已经解决了。
我尝试使用不同的编码,并尝试以二进制模式打开source
文件,但它又出现了另一个错误,因为我忘记了以二进制模式打开destination
文件。
它读取所有字节都很好,写得也很好,以二进制模式打开这两个文件。
在这里,我的代码:
destination = File("file2", "wb")
source = File.open("file1", "rb")
source.each_byte do |byte|
destination.print (byte).chr
end
destination.close
source.close