I’m using Corona SDK Version 3.0.0, Build 2-16.2906, simulator in Windows10.
I need to read a file, byte by byte
I´ve tried opening the file in “rb” mode:
Local file, errorString = io.open (PathAndFileName, “rb”)
byte = file:read ()
Print (“byte =” … string.format ("%x", byte))
Error: bad argument # 2 to ‘format’ (number expected, got string)
How to solve the problem?
Hi. It’s your format() that’s failing. Try it with “%s” rather than “%x”.
or, if you’re trying to do the opposite… then you need a “1” in file:read(1), and to print an 8-bit number with your %x you’ll need to string.byte() it first, fe as a “one-liner” with all the pieces you’d need: print(string.format("%x", string.byte(file:read(1))))
Thanks for the tips.
I also checked the book “Programming in Lua” and found a solution:
local FileName, file, errorString, char, byte
FileName = “xxxxx.wav”
PathAndFileName = system.pathForFile(FileName, system.DocumentsDirectory )
file = io.open( PathAndFileName, “rb” )
bytes = {}
for n = 1, 45 do – first 45 bytes from file
char = file:read(1)
byte = string.byte(char)
bytes[#bytes+1] = byte
end
io.close(file)
Hi. It’s your format() that’s failing. Try it with “%s” rather than “%x”.
or, if you’re trying to do the opposite… then you need a “1” in file:read(1), and to print an 8-bit number with your %x you’ll need to string.byte() it first, fe as a “one-liner” with all the pieces you’d need: print(string.format("%x", string.byte(file:read(1))))
Thanks for the tips.
I also checked the book “Programming in Lua” and found a solution:
local FileName, file, errorString, char, byte
FileName = “xxxxx.wav”
PathAndFileName = system.pathForFile(FileName, system.DocumentsDirectory )
file = io.open( PathAndFileName, “rb” )
bytes = {}
for n = 1, 45 do – first 45 bytes from file
char = file:read(1)
byte = string.byte(char)
bytes[#bytes+1] = byte
end
io.close(file)