This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
gudenau's profile picture

[Solved] File Api Oddness

Started by gudenau, 24 August 2013 - 02:15 PM
gudenau #1
Posted 24 August 2013 - 04:15 PM
So, I have this file and I want to read it, the thing is that at 0x000008 - 0x00000B shoudl read 0x0000000D but when I read it I get 0x504E470D, why is this?


glass = peripheral.wrap('left')
function drawPixel(x_, y_, color_)
glass.addBox(x_ + 16, y_ + 16, 1, 1, color_, 1)
end
function readChunk(handle)
length = bit.blshift(handle.read(), 24) + bit.blshift(handle.read(), 16) + bit.blshift(handle.read(), 8) + handle.read()
print(string.format("%X", length))
end
function drawApple()
appleFile = fs.open('apple.png', 'rb')

if appleFile.read() ~= 0x89 and appleFile.read() ~= 0x50 and appleFile.read() ~= 0x4E and appleFile.read() ~= 0x47 and appleFile.read() ~= 0x0D and appleFile.read() ~= 0x0A and appleFile.read() ~= 0x1A and appleFile.read() ~= 0x0A then
  print("apple.ong is invalid!")
  appleFile.close()
  return false
end

readChunk(appleFile)
end
drawApple()
GopherAtl #2
Posted 24 August 2013 - 04:30 PM
your compound conditional is the problem. It reads the first byte, compares it, and if equals the expected 0x89, it quits immediately.
You need to do all the appleFile.read() calls before the if, then compare them all.
You also probably want to use or instead of and, since it is invalid if any one value doesn't match, rather than only being invalid if none of them match.
gudenau #3
Posted 24 August 2013 - 04:31 PM
I need it to be invalid if one does not match. It is after that that is the problem… As I am reading a PNG file.
GopherAtl #4
Posted 24 August 2013 - 04:38 PM
yes. You need it to be invalid if ONE does not match. As written it is invalid only if NONE match.


if appleFile.read() ~= 0x89 and appleFile.read() ~= 0x50 and appleFile.read() ~= 0x4E and appleFile.read() ~= 0x47 and appleFile.read() ~= 0x0D and appleFile.read() ~= 0x0A and appleFile.read() ~= 0x1A and appleFile.read() ~= 0x0A then

translated to english, "if the first byte is invalid and the second byte is invalid and the third byte is invalid….etc"
you want "or", not "and."

Also, read all the bytes first, as I said. Lua does a form of short-circuiting for expressions, so with "and," once it finds a false, the rest will not run at all - so the later bytes won't be read at all. With "or" this won't matter as much, since it is invalid and you intend to stop reading anyway, but with the "ands" as you haev it now, the first byte is read, matches, so gives false, and it immediately stops and skips the if body. Then you call loadChunk. Notice the bytes you're getting look suspiciously like the magic characters?
gudenau #5
Posted 24 August 2013 - 04:52 PM
Oh… Oops. Thanks.