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

Byte-mashup using fs.open(...) handles

Started by KFAFSP, 21 June 2013 - 01:41 PM
KFAFSP #1
Posted 21 June 2013 - 03:41 PM
Hello Pro's,

I just encountered a very strange problem : I was building a string representing bytes I wanted to write to a file. For faster loading and saving, I decided on using fs.open() file handles. I added the byte 0xED (278d) to the string (with string.char(0xED)), which produced the expected results, but after saving the string to the file a HEX-Editor showed me that insted of 0xED the handle actually comitted 0x3D to the file. Messing around a bit I found out that every value >127 will be strangely deformed when writing to a file, both with fs.open() and io.open(). The only solution I found was using fs/io.open(.., "wb") to write in binary mode, which is (sadly) much slower but in this case precise. The whole reason I was using strings is because it allowed me to read my bytes from a fs.readAll() result string.

Is this problem related to the CC Java implementation or is the textfile loading/saving function actually supposed to work this way?


local hFile = fs.open("/test", "w")
hFile.write(string.char(0xED))
hFile.close()
.
.
.
local hFile = fs.open("/test", "r")
local iByte = string.byte(hFile.readAll(), 1)
hFile.close()
assert(iByte == 0xED, "It will fail...")
theoriginalbit #2
Posted 21 June 2013 - 04:14 PM
Unfortunately you will have to stick with opening the file in binary mode.

This is a bug has been discovered before in other forms:
By NeverCast
By Eric

And as you can see from those threads, sadly it's a won't fix/can't fix from the developers.

Maybe we can hold out hope for the day they replace LuaJ and this bug no longer exists.

— BIT
GravityScore #3
Posted 21 June 2013 - 09:24 PM
I also came across this problem! It really annoyed me, and I stopped working on the project. Thanks for the wb method (the strings I was working with are small)! I never knew… :D/>
LBPHacker #4
Posted 22 June 2013 - 03:15 AM
Another problem that .readAll reads the 0x0D as 0x0A… I could work with 7-bit functions, but reading the CR as LF really messes it up…
Bomb Bloke #5
Posted 22 June 2013 - 06:31 AM
Not helpful, I know, but it sounds related to the upper limit on Java bytes (that being 127) - for who knows what reason, we still don't have unsigned primitives available in that language.