Skip to content

std.fs

Files, paths, and byte-shaped read / write helpers.

std.fs is the safe filesystem surface. It exposes a File handle type and Result-returning helpers for opening, reading, writing, and closing.

export struct File:
fd: c_int
export enum FsError:
case InvalidPath
case NotFound
case PermissionDenied
case Interrupted
case OpenFailed(code: i32)
case ReadFailed(code: i32)
case WriteFailed(code: i32)
case CloseFailed(code: i32)

File has a drop destructor that closes the underlying fd on scope exit. It also exposes:

impl File:
export def close_best_effort(self: mut view File) -> None

which makes it usable with defer and use mut cleanup.

export def open_read(path: view Path) -> Result[File, FsError]
export def file_read(file: mut view File, buf: mut view [u8]) -> Result[usize, FsError]
export def file_close(file: File) -> Result[None, FsError]
export def file_close_best_effort(file: File) -> None
export def open_write_truncate(path: view Path) -> Result[File, FsError]
export def file_write(file: mut view File, bytes: view [u8]) -> Result[usize, FsError]
export def file_write_all(file: mut view File, bytes: view [u8]) -> Result[None, FsError]

open_write_truncate creates the file if missing and truncates it otherwise. file_write issues a single write and returns the number of bytes actually written; file_write_all loops until every byte lands or a write fails.

export def read_file_bytes(path: view Path) -> Result[ByteBuf, FsError]
export def write_file_bytes(path: view Path, bytes: view [u8]) -> Result[None, FsError]

read_file_bytes reads the entire file into an owned ByteBuf. write_file_bytes performs a truncating overwrite (creating the file if missing) and retries partial writes.

import std.fs as fs
import std.io as io
import std.process as process
def main() -> i32:
let path_result: Result[PathBuf, ProcessArgError] = process.process_arg_path(0)
match path_result:
case Ok(path):
let bytes_result: Result[ByteBuf, FsError] = fs.read_file_bytes(path.as_path())
match bytes_result:
case Ok(bytes):
io.stdout_write_bytes(bytes.as_slice())
return 0
case Err:
io.stderr_write_str("read failed\n")
return 1
case Err:
io.stderr_write_str("usage: cat PATH\n")
return 1

See examples/file-io for the annotated long form.