我想打印出特定文件的第7个(或其他)字节和最后一个字节。我想通过命令行使用ruby命令来完成此操作。(我使用的是Mac操作系统,但这无关紧要。)
我该怎么做呢?
发布于 2012-03-10 20:59:00
这会打印出每个字节的整数值,这比您请求在base64中打印更容易理解:
arr = []
f = File.new("/tmp/test.txt")
# "This is a test sentence.\n"
f.seek(7)
# => 0
arr << f.readbyte
# => [32] (The space between 'is' and 'a'.)
f.seek(-1, IO::SEEK_END)
# => 0
arr << f.readbyte
# => [32, 10] (The newline at the end of the file.)发布于 2012-03-10 20:54:33
下面是base64编码的代码:
require 'Base64'
file = File.open("temp.txt", "r")
byte_array = []
file.seek(6) # go to 7th byte
byte_array << file.getbyte
file.seek(file.size - 1)
byte_array << file.getbyte
Base64.encode64(byte_array.pack('c*'))编辑如果您不想显式地使用base64编码,那么您也可以像这样打印字节值:
puts byte_array * " "https://stackoverflow.com/questions/9646505
复制相似问题