ruby - 为什么 Ruby 不读取文件中的所有字节

标签 ruby file

我正在学习 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

我比较原始的 source 图像文件: Original Image

以及新图像 destination: New image

我看到0x0D0x0A对应于\r\n

当我在 irb 中手动测试代码时,我看到可以很好地读取 4 个初始元素,然后忽略第 5 个(0x0D = \r) 元素,并获取下一个 (0x0A = \n)。

当我使用 pdf 文件运行代码时,我在原始文件中看到: Original pdf

在新的 pdf 文件中: New pdf

当我执行 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/

相关文章:

ruby - 使用 openssl 重新编译/重新安装 Ruby 2.0

linux - 将 `struct file` 传递给另一个进程

file - 如何提交非英文文件?

php - 读取文件直到到达一个字符然后用 PHP 写入

c - 在 Windows 上的 C 目录中查找最旧的文件

ruby-on-rails - Ruby 中 Association 的相关内容 (on Rails)

ruby-on-rails - 如何跳过 Rails 中特定功能的模型验证?

ruby - 删除文本文件中的特定行?

c# - 如何从 C# 中的文本文件中获取某些行?

ruby-on-rails - 在 Kaminari 中对多个模型进行分页