ruby way of dumping file

J

Joshua Ball

[Note: parts of this message were removed to make it a legal post.]

Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of printing
out the first 20 bytes of a file? My solution doesn't feel right.

open(ARGV[0], 'rb') { |f|
(0..20).each do |n|
printf "%02d: ", n
f.read(1).each_byte { | b | printf "0x%02x \n", b }
end
}

Thanks.
 
T

The Higgs bozo

Joshua said:
Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of
printing
out the first 20 bytes of a file? My solution doesn't feel right.

print File.read(ARGV.first)[0...20]
 
E

Einar Magnús Boson

Joshua said:
Hi,
Can someone give me a cleaner, more rubyesque (even correct) way of
printing
out the first 20 bytes of a file? My solution doesn't feel right.

print File.read(ARGV.first)[0...20]


Doesn't that read the entire file before extracting the first 20
bytes? Seems silly to me.

rather something like this:

open ARGV.first, "rb" do |f|
read = ""
begin
read += f.read(20)
end while read.size < 20 && !f.eof?
p read[0...20]
end

although I suppose this would work too:

p open(ARGV[0], "rb"){|f|f.read(20)}

but I don't think read(20) is guaranteed to read 20 bytes but maybe
that is just in sockets.

einarmagnus
 
P

Peña, Botp

From: Joshua Ball [mailto:[email protected]]=20
# Can someone give me a cleaner, more rubyesque (even correct)=20
# way of printing out the first 20 bytes of a file? My solution
# doesn't feel right.
#=20
# open(ARGV[0], 'rb') { |f| ...


try,

IO.read ARGV[0], 20
 
B

Brian Candler

Einar said:
p open(ARGV[0], "rb"){|f|f.read(20)}

but I don't think read(20) is guaranteed to read 20 bytes but maybe
that is just in sockets.

In Ruby, I believe it's guaranteed to read 20 bytes, from both files and
sockets - it will restart the underlying OS calls if necessary - unless
EOF is reached.

I think the each_byte approach is cleanest, but here are some
alternatives:

# not ruby-1.9 clean
puts File.read(ARGV[0],20).gsub(/(.)/) { "0x%02x\n" % $1[0] }

# different output format
puts File.read(ARGV[0],20).unpack("H*")[0].scan(/../).join(" ")
puts File.read(ARGV[0],20).unpack("H2 "*20).join(" ")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top