我正在学习 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"
字符串中获取十进制值吗?
最佳答案
已经解决了。
我尝试使用不同的编码,我尝试以二进制模式打开 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
关于ruby - 为什么 Ruby 不读取文件中的所有字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347284/