LEARN VOID

Files and host paths

Extract a filename and handle a filesystem operation through its result.

files-paths.voidDownload source
use path

func entry(offset: i32) -> i32:
    if path.filename("atlas/map.txt") is Ok(var name):
        return (name.length as i32) + offset
    return 0
Input 0Expected result 7

Separate the filename

This example asks for the filename in a relative path. It needs no existing file. The name “map.txt” has seven scalars. A failed path operation returns an error, handled here by returning zero.

Open a file deliberately

use io provides io.open(path, io.open_mode.read). Match the result before using the file. read_bytes allows short reads. read_exact asks for an exact byte count.

Finish using the handle

Use close() when the outcome matters, or scoped with for deterministic cleanup. Do not rely on garbage collection to close files. Inspect the returned I/O error for operation, path and partial progress. Host path syntax and separators depend on platform.

Read a fixed-size field

Set VOID_GUIDE_FILE to a three-byte file. Asking for two bytes returns two. Asking for four returns the example’s failure value, −1. The with scope releases the handle on both paths.

count-bytes.voidDownload source
use io
use os

func sample_size(filename: string, wanted: i32) -> result<i32, io.error>:
    with io.open(filename)? as handle:
        var block = handle.read_exact(wanted as i64)?
        return Ok(block.count as i32)

func entry(wanted: i32) -> i32:
    if os.env("VOID_GUIDE_FILE") is Ok(var filename):
        if sample_size(filename, wanted) is Ok(var count):
            return count
    return -1
Input 2Expected result 2

Continue learning with Application directories · Results and errors.