In similar question people recommend use File.read to read a whole file. But when I try to read png file (see fig. 1) I get only first line (see fig. 2). What am I doing wrong?
在类似的问题中,人们建议使用File.read来读取整个文件。但是当我尝试读取png文件时(见图1),我只得到第一行(见图2)。我究竟做错了什么?
1 个解决方案
#1
Use File.binread
to read binary data.
使用File.binread读取二进制数据。
On certain operating systems (notably Windows), there is a difference between opening a file in "binary mode" (8-bit characters) and "text mode" (7-bit characters). Because of this, these IO implementations can do things like detect end-of-file when there is a zero character, or mangle up characters outside of the ASCII range if you don't tell them to expect binary data.
在某些操作系统(特别是Windows)上,以“二进制模式”(8位字符)和“文本模式”(7位字符)打开文件之间存在差异。因此,这些IO实现可以执行诸如在存在零字符时检测文件结束,或者如果您不告诉它们期望二进制数据那么将字符数字加到ASCII范围之外。
If you open a file in Ruby, using mode "rb" instead of "r" will tell the OS that you expect binary data, and if it cares about that, it will do the right thing. File.binread()
opens the underlying file it will read from with that mode.
如果你在Ruby中打开一个文件,使用模式“rb”而不是“r”将告诉操作系统你期望二进制数据,如果它关心它,它将做正确的事情。 File.binread()打开它将使用该模式读取的基础文件。
#1
Use File.binread
to read binary data.
使用File.binread读取二进制数据。
On certain operating systems (notably Windows), there is a difference between opening a file in "binary mode" (8-bit characters) and "text mode" (7-bit characters). Because of this, these IO implementations can do things like detect end-of-file when there is a zero character, or mangle up characters outside of the ASCII range if you don't tell them to expect binary data.
在某些操作系统(特别是Windows)上,以“二进制模式”(8位字符)和“文本模式”(7位字符)打开文件之间存在差异。因此,这些IO实现可以执行诸如在存在零字符时检测文件结束,或者如果您不告诉它们期望二进制数据那么将字符数字加到ASCII范围之外。
If you open a file in Ruby, using mode "rb" instead of "r" will tell the OS that you expect binary data, and if it cares about that, it will do the right thing. File.binread()
opens the underlying file it will read from with that mode.
如果你在Ruby中打开一个文件,使用模式“rb”而不是“r”将告诉操作系统你期望二进制数据,如果它关心它,它将做正确的事情。 File.binread()打开它将使用该模式读取的基础文件。