std.fs
API summary (generated from the Beans source by npm run coverage): 7 package functions.
std.fs gives you one-call helpers to read or write a whole file. Under the hood
it opens a File, does the work, and closes it.
Read the source at
stdlib/std/fs/fs.b.
Every function returns a Result, because
filesystem work can fail. Use ? to pass the error up.
import std.fsReading
Section titled “Reading”pub fn read_bytes(path: string) -> Result<Bytes>pub fn read(path: string) -> Result<string>read_bytesopens the file, reads it whole from offset 0, and returns the bytes.readdoes the same and fills its returned string directly. It does not build an intermediateBytesvalue.
Writing
Section titled “Writing”pub fn write_bytes(path: string, data: Bytes) -> Result<int>pub fn write(path: string, data: string) -> Result<int>pub fn append_bytes(path: string, data: Bytes) -> Result<int>pub fn append(path: string, data: string) -> Result<int>pub fn copy(from: string, to: string) -> Result<int>All five return the number of bytes written.
write_bytesandwriteopen the file in “create” mode, truncate it to empty, and write starting at position 0.writetakes a string;write_bytestakesBytes. Text writes use the string storage directly.append_bytesandappendopen the file in “append” mode and adddatato the end instead of truncating.copyuses the platform file-copy path when available and a fixed-size fallback. It does not hold the whole source file in a Beans buffer. A same-file or hard-link copy fails before the destination can be truncated.
import std.ioimport std.fs
fn main() { fs.write("greeting.txt", "hello\n").expect("write") fs.append("greeting.txt", "again\n").expect("append") let text: string = fs.read("greeting.txt").expect("read") io.print(text) // hello / again}See also
Section titled “See also”- Files and mapping, the
Filetype for positional and cursor I/O when you need finer control. - std.path, build the path strings you pass here.
- std.reader, read a file line by line instead of all at once.