I am learning ruby, and I want to read a file bytewise. It work fine with short text files, but It stop reading bytes when I try it with an image or pdf file.
I tried different implementations but I got the same result. Here is my code:
destination = File("file2", "w")
source = File.open("file1", "r")
source.each_byte do |byte|
destination.print (byte).chr
end
destination.close
I tried this too:
destination = File("file2", "w")
source = File.open("file1", "r")
source.each_byte do |byte|
destination.putc(byte)
end
destination.close
I compare the original source
image file:
And the new image destination
:
I saw that 0x0D
and 0x0A
correspond with \r
and \n
.
When I test the code manually in irb
I see that read fine the 4 initial elements, and then ignore the 5th (0x0D
= \r
) element, and get the next one (0x0A
= \n
).
When I run the code with a pdf file, I see that in the original file:
When I do source.read(1)
I get the correct values \r
and \n
.
Why .getbyte
ignore the 0x0D
byte (\r
), and say that there aren't more bytes?
Can I get the decimal value from the "\r"
and "\n"
strings?