Skip to content

Files and the System

The io functions that can fail return an Error as the last value.

import @io
do main() {
mut written, write_err = io.write_file("notes.txt", "first line\nsecond line\n")
if write_err != nil {
println("write failed: ${write_err}")
exit(1)
}
mut lines, read_err = io.read_lines("notes.txt")
if read_err != nil {
println("read failed: ${read_err}")
exit(1)
}
for_each line in lines {
println(line)
}
println(written)
}

Check a path before using it.

import @io
import @path
do main() {
if io.file_exists("notes.txt") {
mut size, err = io.file_size("notes.txt")
if err == nil {
println(size)
}
}
println(path.join_parts({"/home", "user", "docs"}))
}
import @os
do main() {
println(os.cpu_count() > 0)
mut home string = os.home_dir()
println(len(home) > 0)
when os.current_os() {
is .LINUX { println("linux") }
is .MAC_OS { println("macos") }
default { println("other") }
}
}

os.exec runs a program and returns an ExecResult with its exit_code, stdout, and stderr. The error is non-nil only when the program could not be launched; a non-zero exit code is not an error.

import @os
do main() {
mut result, err = os.exec("echo", {"hello"})
if err != nil {
println("could not launch")
exit(1)
}
println("${result.exit_code}: ${result.stdout}")
println(len(result.stderr))
}