3

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: Original Image

And the new image destination: New image

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: Original pdf

And this in the new pdf file: New pdf

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?

Barrendeitor
  • 506
  • 1
  • 3
  • 14

1 Answers1

1

Already solved.

I was trying with different encodings, and I tried opening the source file in binary mode, but It got another error because I forgot open the destination file in binary mode too.

It read all bytes fine, and write fine too, opening both files in binary mode.

Here, my code:

destination = File("file2", "wb")
source = File.open("file1", "rb")
source.each_byte do |byte|
    destination.print (byte).chr
end
destination.close
source.close
Barrendeitor
  • 506
  • 1
  • 3
  • 14