gpt4 book ai didi

ruby - 如何在 Ruby 1.9 中读取文件中的字节?

转载 作者:数据小太阳 更新时间:2023-10-29 07:57:19 27 4
gpt4 key购买 nike

在 Ruby 1.9 中,文件和 IO 库发生了变化——它们现在似乎总是将数据解释为编码字符串(例如 UTF-8),并且返回值似乎总是字符串。

我需要在 Ruby 1.9 中逐字节读取文件,而不对数据进行任何修改或解释。我想读取字节序列,而不是编码字符串。

关于如何最好地做到这一点有什么建议吗?

最佳答案

我在我写的 gem 中遇到了类似的问题。这是相关代码:(你不需要 require 语句)

# ==============================================================================
# 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

关于ruby - 如何在 Ruby 1.9 中读取文件中的字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com