在Ruby 1.9中,如何从文件中读取字节?
在Ruby 1.9中,文件和IO库发生了变化——它们现在似乎总是将数据解释为编码字符串(例如UTF-8),并且返回的值似乎总是字符串 我需要一个字节一个字节地读取Ruby 1.9中的文件,而不需要对数据进行任何修改或解释。 我想读取字节序列,而不是编码字符串在Ruby 1.9中,如何从文件中读取字节?,ruby,Ruby,在Ruby 1.9中,文件和IO库发生了变化——它们现在似乎总是将数据解释为编码字符串(例如UTF-8),并且返回的值似乎总是字符串 我需要一个字节一个字节地读取Ruby 1.9中的文件,而不需要对数据进行任何修改或解释。 我想读取字节序列,而不是编码字符串 关于如何最好地做到这一点,有什么建议吗?在我写的gem中,我也遇到了类似的问题。以下是相关代码: (您不需要require语句) #======================================================
关于如何最好地做到这一点,有什么建议吗?在我写的gem中,我也遇到了类似的问题。以下是相关代码: (您不需要require语句)
#==============================================================================
#加载Ruby 1.9和1.8兼容性所需的库和内容
# ==============================================================================
#这里的想法是为不同的类定义两个中间方法
#根据Ruby版本的不同,它们的定义也有所不同
#从这些类的特定Ruby版本的API中提取
如果RUBY_版本>=“1.9.0”
需要“摘要/md5”
需要“摘要/sha1”
包括摘要
需要“fileutils”替换ftools
include FileUtils::Verbose
类文件
def read_bytes(n)#返回包含字节的字符串
self.bytes.take(n)
结束
def写入字节(字节)
self.syswrite(字节)
结束
def get_字节
self.getbyte#返回一个数字0..255
结束
结束
ZEROBYTE=“\x00”。是否强制_编码(编码::二进制),除非已定义?零字节
else#较旧的Ruby版本:
需要“rubygems”
需要“md5”
需要“sha1”
需要“ftools”
def移动(a、b)
文件移动(a,b)
结束
类字符串
def getbyte(x)#访问字符串并选择第x个字节进行计算时,如Ruby 1.9中所定义
self[x]#返回一个整数
结束
结束
类文件
def读取字节(n)
self.read(n)#这里也应该使用sysread吗?
结束
def写入字节(字节)
self.write(字节)#也应该在这里使用syswrite吗?
结束
def get_byte#在较旧的Ruby版本中IO具有binmode方法(调用它就是设置它),该方法禁用换行和编码转换。File类继承了这个方法。从Ruby 2.0.0及更高版本开始,IO#每个#u字节
都优先于IO#字节
。
# ==============================================================================
# Loading Libraries and Stuff needed for Ruby 1.9 vs 1.8 Compatibility
# ==============================================================================
# the idea here is to define a couple of go-between methods for different classes
# which are differently defined depending on which Ruby version it is -- thereby
# abstracting from the particular Ruby version's API of those classes
if RUBY_VERSION >= "1.9.0"
require "digest/md5"
require "digest/sha1"
include Digest
require 'fileutils' # replaces ftools
include FileUtils::Verbose
class File
def read_bytes(n) # returns a string containing bytes
self.bytes.take(n)
end
def write_bytes(bytes)
self.syswrite(bytes)
end
def get_byte
self.getbyte # returns a number 0..255
end
end
ZEROBYTE = "\x00".force_encoding(Encoding::BINARY) unless defined? ZEROBYTE
else # older Ruby versions:
require 'rubygems'
require "md5"
require "sha1"
require 'ftools'
def move(a,b)
File.move(a,b)
end
class String
def getbyte(x) # when accessing a string and selecting x-th byte to do calculations , as defined in Ruby 1.9
self[x] # returns an integer
end
end
class File
def read_bytes(n)
self.read(n) # should use sysread here as well?
end
def write_bytes(bytes)
self.write(bytes) # should use syswrite here as well?
end
def get_byte # in older Ruby versions <1.9 getc returned a byte, e.g. a number 0..255
self.getc # returns a number 0..255
end
end
ZEROBYTE = "\0" unless defined? ZEROBYTE
end