Skip to content

File I/O

A cat-style program: read a path from argv, dump its contents to stdout.

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

What’s worth noticing:

  • process.process_arg_path(0) returns the first program argument as a PathBuf. The path form is byte-shaped (InvalidUtf8 is not a possible error here, unlike process_arg).
  • path.as_path() produces a view Path: a borrowed view of the owned PathBuf.
  • fs.read_file_bytes(...) opens, reads to EOF, and closes the file as a single Result-returning operation. The returned ByteBuf is owned by this scope and will be dropped at function exit.
  • file.as_slice() produces view [u8] over the owned buffer: the borrow is tied to the buffer’s lifetime.

For the longer pipeline-shaped version (writes to a destination path, dispatches errors via a custom enum), see examples/cli/copy_checked.zmeu in the repo.