Quirrel4.41.0

iostream.stream.readn

Method of stream, from module "iostream"
instance.readn(format: int): number

Reads a value of the given numeric format and returns it

examples/iostream/stream/readn-basic.nut
from "iostream" import blob

let hp = blob(0)
hp.writen(100, 'i')
hp.seek(0)
println("hp.readn('i') =", hp.readn('i'))
Output:
hp.readn('i') = 100

Parameters

formatinta character selecting the numeric type and width to read

Return value

An int for every integer format, a float for 'f' and 'd'.

writen writes the same eight codes at the same widths.

Bytes are copied verbatim, in the host's native byte order (little-endian on every platform this engine targets); readn never swaps bytes on its own. A value written and read back on the same platform always round-trips, but exchanging the raw bytes with a big-endian peer needs a byte swap first, such as iostream.swap2 or iostream.swap4.

Errors

Throws io error when fewer bytes than the format's width remain before len.

Throws invalid format when format is not one of the eight codes above.

Notes

The same method works on a file: it reads at the file's current position and advances it by the format's width, the same as it moves a blob's cursor.

Example

examples/iostream/stream/readn.nut
from "iostream" import blob

let b = blob(0)                 // grows to fit as each write extends past the end
b.writen(0x0102030405060708, 'l') // 8-byte native integer
b.writen(-7, 'c')                 // 1-byte signed
println("b.len() =", b.len())                  // 8 + 1 = 9

b.seek(0)
println("b.readn('l') == 0x0102030405060708 =", b.readn('l') == 0x0102030405060708)
println("b.readn('c') =", b.readn('c'))

b.seek(-1, 'e')                   // 1 byte left before len, 'i' needs 4
try { b.readn('i') } catch (e) { println("b.readn('i') throws:", e) }
try { b.readn('z') } catch (e) { println("b.readn('z') throws:", e) } // 'z' is not a format code
Output:
b.len() = 9
b.readn('l') == 0x0102030405060708 = true
b.readn('c') = -7
b.readn('i') throws: io error
b.readn('z') throws: invalid format

See also

readnReads a value of the given numeric format and returns it
writenWrites a numeric value in the given format
seekSeeks to the given offset; origin is 'b' (begin), 'c' (current) or 'e' (end)
swap2Byte-swaps a 16-bit value
streamclass index