打印出文件的第n个字节和最后一个字节

时间:2012-03-10 12:42:19

标签: ruby

我想打印出特定文件的第7个(或其他)字节和最后一个字节。我想使用ruby命令通过命令行执行此操作。 (我在Mac OS X上,但没关系。)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

以下是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 * " "

答案 1 :(得分:1)

这将打印每个字节的整数值,这比您在base 64中打印的请求更容易理解:

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.)