在Ruby中读取整个文件(可能是一个bug) [英] Reading a whole file in Ruby (possibly a bug)

查看:131
本文介绍了在Ruby中读取整个文件(可能是一个bug)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似问题中,人们建议使用File.read进行阅读整个文件。但是当我尝试读取png文件时(见图1),我只得到第一行(见图2)。我究竟做错了什么?

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.binread 读取二进制数据。

在某些操作系统(特别是Windows)上,打开二进制文件之间存在差异模式(8位字符)和文本模式(7位字符)。因此,如果没有告诉他们期望二进制数据,这些IO实现可以执行诸如在零字符时检测文件结尾,或者在ASCII范围之外编写字符的情况。

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.

如果你在Ruby中打开一个文件,使用模式rb而不是r将告诉操作系统你期望二进制数据,如果它关心它,它会做正确的事情。 File.binread()打开它将使用该模式读取的基础文件。

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中读取整个文件(可能是一个bug)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆