Weird behaviour of File.open

Can’t figure out what’s happening here

 Erlang/OTP 27 [erts-15.2] [source] [64-bit] [smp:10:10] [ds:10:10:10] [async-threads:1] [jit] 

Elixir 1.18.0 (compiled with Erlang/OTP 27)
iex(1)> File.open("/tmp/x.png", [:read, :binary], fn f -> IO.read(f, 1000) end)
{:ok,
 <<194, 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 7,
   39, 0, 0, 2, 195, 164, 8, 6, 0, 0, 0, 194, 165, 123, 57, 194, 133, 0, 0, 1,
   90, 105, 67, 67, 80, 73, 67, 67, ...>>}
iex(2)> File.read("/tmp/x.png")
{:ok,
 <<137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 7, 39, 0,
   0, 2, 228, 8, 6, 0, 0, 0, 165, 123, 57, 133, 0, 0, 1, 90, 105, 67, 67, 80,
   73, 67, 67, 32, 80, 114, 111, ...>>}
iex(3)>

PNG file starts with bytes 137, 80 and so on, but IO.read inside File.open inserts extra byte at the beginning

Looks like any file containing bytes with MSB set gets screwed up

Use IO.binread - IO.read is specified to return a valid UTF-8 string

2 Likes

Thanks, that helps!