Quirrel4.41.0

iostream.stream.writen

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

Writes a numeric value in the given format

examples/iostream/stream/writen-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

valuenumberthe value to write
formatinta character selecting the numeric type and width to write

Notes

readn reads back the same eight codes at the same widths:

Bytes are stored verbatim, in the host's native byte order (little-endian on every platform this engine targets); writen never swaps bytes on its own. Pair it with a byte swap, such as iostream.swap2 or iostream.swap4, before handing the bytes to a big-endian peer.

The same method works on a file: it writes at the file's current position and advances it by the format's width, the same as it moves a blob's cursor. Writing past the current len grows a blob to fit; writing past the end of a file extends the file the same way, since both are ordinary writes to the underlying medium.

Errors

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

writen also throws io error if the underlying stream cannot store the full width, for example a file opened read-only; a blob's own storage never refuses a write, so this case cannot happen on a blob.

Example

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

let b = blob(0)         // empty; every write below extends it
b.writen(0x11223344, 'i') // 4 bytes
println("b.len() after writen('i') =", b.len())
b.writen(2.5, 'f')        // writing past the end grows the blob, never an error
println("b.len() after writen('f') =", b.len())

b.seek(0)
println("b.readn('i') == 0x11223344 =", b.readn('i') == 0x11223344)
println("b.readn('f') =", b.readn('f'))

try { b.writen(1, 'z') } catch (e) { println("b.writen(1, 'z') throws:", e) } // 'z' is not a format code
Output:
b.len() after writen('i') = 4
b.len() after writen('f') = 8
b.readn('i') == 0x11223344 = true
b.readn('f') = 2.5
b.writen(1, 'z') throws: invalid format

See also

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