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

Reading Bytes and ... er not

Started by HPWebcamAble, 23 June 2015 - 11:07 PM
HPWebcamAble #1
Posted 24 June 2015 - 01:07 AM
Using fs.open("file","r") and fs.open("file","rb") are similar

But what are the benefits to using 'rb' mode?


Is there ever a situation when you CAN't do this:

f = fs.open("file","r")
local firstByte = string.byte( f.readLine() )
f.close()
and would therefore need to use 'rb' mode?


f = fs.open("file","rb")
local firstByte = f.read()
f.close()
Bomb Bloke #2
Posted 24 June 2015 - 01:16 AM
Yeah, pretty much whenever the file contents can't be represented in vanilla ASCII.

For eg, let's say you wrote a file like this:

local file = fs.open("someFile", "wb")
file.write(219)
file.close()

Reading the file in text mode:

local file = fs.open("someFile", "r")
local input = file.readAll()
file.close()

for i = 1, #input do
  print(input:byte(i))
end

This outputs 239 190 155, which is obviously not what you'd want. Note that this is not the fault of string.byte(), or an inaccuracy with #input - they both work correctly with a string formed with, say, string.char(219).

In binary mode:

local file = fs.open("someFile", "rb")

for byte in file.read do
  print(byte)
end

file.close()

This outputs 219.

In short, if you want to read text, go ahead and use text mode. If you want to read anything, use binary mode.
Edited on 23 June 2015 - 11:18 PM
HPWebcamAble #3
Posted 24 June 2015 - 01:57 AM
Thanks, makes a lot of sense :)/>