system.fs
system.fs reaches the filesystem through an Fs handle. The handle is the capability: a function that is not given one cannot read or write a file, so the ability to touch the disk is visible in a signature instead of ambient across the whole program.
use system.io
use system.fs
fn main()
// An Fs handle is the capability: a function without one cannot touch
// the filesystem at all.
let fs = Fs()
let path = "/tmp/miri-notes.txt"
match fs.write_file(path, "first line\n")
Result.Ok(written): println(f"wrote {written} bytes")
Result.Err(e): println(f"write failed: {e}")
match fs.append_file(path, "second line\n")
Result.Ok(written): println(f"appended {written} bytes")
Result.Err(e): println(f"append failed: {e}")
match fs.read_file(path)
Result.Ok(text): println(f"read {text.length()} chars")
Result.Err(e): println(f"read failed: {e}")
println(f"exists: {fs.exists(path)}")
match fs.delete(path)
Result.Ok(removed): println(f"deleted: {removed}")
Result.Err(e): println(f"delete failed: {e}")
| Method | Returns |
|---|---|
exists(path String) | bool |
read_file(path String) | Result<String, FsError> |
write_file(path String, contents String) | Result<int, FsError> — bytes written |
append_file(path String, contents String) | Result<int, FsError> — bytes appended |
list_dir(path String) | Result<[String], FsError> |
create_dir(path String) | Result<bool, FsError> |
delete(path String) | Result<bool, FsError> |
cwd() | Result<String, FsError> |
FsError distinguishes NotFound, PermissionDenied, AlreadyExists, NotADirectory, InvalidData and Other, each carrying a message. It is @non_exhaustive, so a match on it needs a default arm and stays compiling when a future release adds a case.