Guides / Standard library

Standard library

Read a message from disk with std/fs. The same import style works for the rest of Silk's standard library.

Read a file#

With Silk installed, save this as read-message.slk:

import fs from "std/fs";
import { println } from "std/io";

fn main () -> int {
  match (fs::read_file_string("message.txt")) {
    Ok(s) => {
      println("{s}", s.as_string());
      return 0;
    },
    Err(e) => {
      // A real program would format/inspect `e.kind()` and report it.
      println("read failed");
      return 1;
    },
  }
}

Create the input and run the program:

printf 'Delivery confirmed\n' > message.txt
mkdir -p build
silk build read-message.slk -o build/read-message
./build/read-message

Expect Delivery confirmed. Remove message.txt and run again: expect read failed and exit status 1.

Ok carries the owned text; as_string() exposes a view for printing. Filesystem APIs describe the error types and file handles.

Choose the next module#

Task Reference
Print or stream data std/io
Build an owned string std/strings
Read configuration std/toml
Exchange structured data std/json
Run concurrent work Concurrency tutorial
Run device code CPU/GPU walkthrough

For return types, follow optionals and results. The module index covers the full library.

Source repository · Edit this page · View Markdown

Quick links

Type to search across the site. Use the up and down arrow keys to choose a result, Enter to open it, and Escape to close.