-->
Page 1 of 2

file.read() stops at string.char(255)

PostPosted: Thu Jan 08, 2015 2:22 am
by Markus Gritsch
The recently added file.read() function has a bug which prevents it from reading binary data which contains a 0xFF byte.

The problem seems to be caused by some EOF checking using an int value of -1 in combination with (signed char) casting of the read character: If the read byte is 255 and then casted to (signed char) this equals to -1 and the function wrongly assumes EOF is reached.

The following test program
Code: Select allfname = 'test.txt'

file.remove(fname)
file.open(fname, 'w')
file.write(string.char(65, 66, 67, 255, 68, 69, 70))
file.close()

print(file.list()[fname] .. ' bytes written')

file.open(fname, 'r')
cont = file.read()
file.close()
print(#cont .. ' bytes read with file.read()')
print(string.byte(cont,1,-1))

gives this output:
Code: Select all7 bytes written
3 bytes read with file.read()
65  66  67

Re: file.read() stops at string.char(255)

PostPosted: Thu Jan 08, 2015 3:29 am
by zeroday
Markus Gritsch wrote:The recently added file.read() function has a bug which prevents it from reading binary data which contains a 0xFF byte.

The problem seems to be caused by some EOF checking using an int value of -1 in combination with (signed char) casting of the read character: If the read byte is 255 and then casted to (signed char) this equals to -1 and the function wrongly assumes EOF is reached.

The following test program
Code: Select allfname = 'test.txt'

file.remove(fname)
file.open(fname, 'w')
file.write(string.char(65, 66, 67, 255, 68, 69, 70))
file.close()

print(file.list()[fname] .. ' bytes written')

file.open(fname, 'r')
cont = file.read()
file.close()
print(#cont .. ' bytes read with file.read()')
print(string.byte(cont,1,-1))

gives this output:
Code: Select all7 bytes written
3 bytes read with file.read()
65  66  67


build 20150108.

Re: file.read() stops at string.char(255)

PostPosted: Thu Jan 08, 2015 3:57 am
by Markus Gritsch
Thanks zeroday, you are the best! It works perfectly now, and for the first time my webserver can now deliver small images! Nice.

Re: file.read() stops at string.char(255)

PostPosted: Thu Jan 08, 2015 1:22 pm
by alonewolfx2
Markus Gritsch wrote:Thanks zeroday, you are the best! It works perfectly now, and for the first time my webserver can now deliver small images! Nice.

can you share example? i am so excited :)