Standard Library: File
The file module provides high-level filesystem operations for reading and
writing text files. All operations go through a filesystem provider, which
means they work transparently with sandboxed and virtual filesystems.
For lower-level I/O (handles, seeking, raw bytes, network, processes), see Standard Library: I/O.
Importing
Section titled “Importing”from std::core::file use { read_text, write_text, read_lines, append }Functions
Section titled “Functions”file::read_text
Section titled “file::read_text”Read the entire contents of a file as a UTF-8 string.
let content = file::read_text("config.toml")?print(content)file::write_text
Section titled “file::write_text”Write a string to a file, creating it if it does not exist or truncating it if it does.
file::write_text("output.txt", "Hello, Shape!")?file::read_lines
Section titled “file::read_lines”Read a file and return its lines as an array of strings.
let lines = file::read_lines("data.csv")?for line in lines { print(line)}file::append
Section titled “file::append”Append a string to a file, creating it if it does not exist.
file::append("log.txt", "new log entry\n")?Function Reference
Section titled “Function Reference”| Function | Signature | Description |
|---|---|---|
file::read_text(path) | (string) -> Result<string, string> | Read file as UTF-8 string |
file::write_text(path, content) | (string, string) -> Result<(), string> | Write string to file |
file::read_lines(path) | (string) -> Result<Array<string>, string> | Read file as array of lines |
file::append(path, content) | (string, string) -> Result<(), string> | Append string to file |
Working With Bytes
Section titled “Working With Bytes”The file module exposes only text-level operations. To read or write raw
byte arrays, use the io module’s handle-based API:
use std::core::io
let f = io::open("image.png", "r")let bytes = io::read_bytes(f, 1024)// f auto-closes when it goes out of scopeSee Standard Library: I/O for the full handle-based API
including io::read_bytes, io::write, and async variants like
io::read_file_async, io::read_bytes_async.
Permissions
Section titled “Permissions”Read operations (read_text, read_lines) require the FsRead permission.
Write operations (write_text, append) require the FsWrite permission.
See Security & Permissions for details.
See Also
Section titled “See Also”- Standard Library: I/O — lower-level I/O with handles, seeking, raw bytes, network, and processes
- Security & Permissions — filesystem permission gating