lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Why would anyone expect io.lines to read binary files correctly?  Binary files have no concept of a 'line'...

Mike

On Fri, Sep 9, 2011 at 7:57 PM, waspoza <waspoza@gmail.com> wrote:
On Fri, Sep 9, 2011 at 6:55 PM, waspoza <waspoza@gmail.com> wrote:
> Yes, this code is probably with errors. It does correct checksums for
> text files, but incorrect for binary files:

> ~/lua$ lua sha256.lua test.jpg -
> 969906c25ee94d6c14aca4edb9b48a1fb350331bd244781d5046699e02d2654c
>
> ~/lua$ sha256sum test.jpg
> fba5916247f503d4792f36af35f1356337e97073ba08b373059e33ab795b035e  test.jpg

Ok, I found the bug. Instead:

-- read a file and prints its hash, if given a file name

if arg[1] then
 local x = sha2.new256()
 for b in io.lines(arg[1], 2^12) do
   x:add(b)
 end
 print(x:close())
end

should be something like this:

if arg[1] then
 file = io.open (arg[1] , 'rb')
 local x = sha2.new256()
 while true do
   b = file:read(2^12)
   if not b then break end
   x:add(b)
 end
 file:close()
 print(x:close())
end

Its uglier, but gives correct checksums.
Looks like io.lines can't read binary files. :(