---
title: "Files"
description: "Read, write, inspect, and stream filesystem entries."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.atoll.workreef.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Files

> **What answers these calls**
>
> `atoll_hosts::files`, over `tokio::fs` — one open-file table per store, and
> every syscall on the blocking pool rather than on the reactor's thread. A
> path crosses as the span of bytes the program keeps it in, read where it lies;
> a file's bytes never cross as a copy, in either direction: the guest supplies
> the block and the kernel reads into it or writes out of it where it already is.
>
> The behaviour described below is measured against that host by the rows in
> `crates/atoll/tests/`, not asserted.

`fs` is a module — `import fs` — and `fs.File` and `fs.Dir` are stateless
namespaces within it over host filesystem operations;
`fs.OpenFile` is a live host resource. Every operation suspends, and every
operation except `fs.File.exists` / `fs.Dir.exists` returns `Result[T, fs.Error]`.

## Names are paths

A file's name is bytes the operating system chose, and on Unix they need not be
UTF-8. Every operation takes its name as a `path.Path` or as a `string`, so
`fs.File.read("a.txt")` is written as it always was, and
`fs.File.read(entry.path)` opens a file whose name is not text. The
[`path`](https://docs.atoll.workreef.dev/language/standard-library/paths/) module says what a `Path` is and
how to take one apart. The host never checks a name for UTF-8, in either
direction: a listing answers each entry's path as the bytes the directory holds,
an `fs.Error` names its path in those bytes, and a program that wants text asks
for it with `Path.to_str`, which says where the bytes stop being text.

A `string` is UTF-8 and so already a path; handing one to `fs` views its bytes
in place, and nothing is copied or checked. A name the kernel cannot take, an
empty one or one with a NUL in it, is `InvalidPath`, naming it.

## Reading a whole file

The smallest useful program: propagate the `Result` with `?` from a fallible
function.

```atoll
import fs

fn read_config(path string) string ! fs.Error {
    return fs.File.read(path)?
}

fn main() void {
    match read_config("/etc/hostname") {
        Ok(text) => println("${text.len()} bytes")
        Err(e) => println("could not read config")
    }
}
```

`?` needs an enclosing fallible function. Dropping the `! fs.Error` from the
signature is the most common first mistake:

```atoll refused=ATOLL2002
import fs

fn read_config(path string) string {
    return fs.File.read(path)?
}
```

That is `ATOLL2002`: *`?` passes this error on, and `read_config` declares no
error to pass it to*, with the signature that would — `fn read_config(…) string
! fs.Error`.
Returning the call without `?` fails too — the type is `Result[string, fs.Error]`,
not `string`.

## The whole-file surface

| Method | Result payload |
| --- | --- |
| `fs.File.read(path)` | UTF-8 `string` |
| `fs.File.read_bytes(path)` | Owned `[]byte` |
| `fs.File.read_bytes_zerocopy(path)` | Owned `[]byte`, filled in place |
| `fs.File.read_lines(path)` | Owned `[]string`, split as `lines()` splits: a `\r` before the `\n` is part of the break, and an empty file has no lines |
| `fs.File.write(path, text)` | `void` — create or replace |
| `fs.File.write_bytes(path, bytes)` | `void` — create or replace |
| `fs.File.append(path, text)` | `void` — create if absent |
| `fs.File.append_bytes(path, bytes)` | `void` |
| `fs.File.copy(src, dst)` | `void` |
| `fs.File.move(src, dst)` | `void` — rename or move |
| `fs.File.delete(path)` | `void` — `NotFound` when missing |
| `fs.File.delete_if_exists(path)` | `void` — succeeds when missing |
| `fs.File.exists(path)` | `bool`, not a `Result` |

```atoll
import fs

fn round_trip(path string) int ! fs.Error {
    fs.File.write(path, "alpha\nbeta\n")?
    fs.File.append(path, "gamma\n")?

    text := fs.File.read(path)?
    lines := fs.File.read_lines(path)?
    raw := fs.File.read_bytes(path)?
    println("${text.len()} bytes, ${lines.len()} lines, ${raw.len()} raw")

    backup := "${path}.bak"
    fs.File.copy(path, backup)?
    println("backup present = ${fs.File.exists(backup)}")

    fs.File.delete(backup)?
    fs.File.delete_if_exists(path)?
    return lines.len()
}

fn main() void {
    match round_trip("/tmp/atoll-book-demo.txt") {
        Ok(n) => println("wrote ${n} lines")
        Err(e) => println("io failure")
    }
}
```

`read_bytes_zerocopy` reads metadata first, sizes one guest buffer, then fills
it directly from the kernel — no host staging copy. It costs two extra
round-trips, so it pays off on large binary files and not on small ones.

```atoll
import fs

fn byte_count(path string) int ! fs.Error {
    raw := fs.File.read_bytes_zerocopy(path)?
    return raw.len()
}

fn checksum(path string) int ! fs.Error {
    raw := fs.File.read_bytes(path)?
    mut sum := 0
    for b in raw {
        sum = sum + int(b)
    }
    return sum
}

fn main() void {
    match byte_count("/etc/hostname") {
        Ok(n) => println("${n} bytes")
        Err(e) => println("unreadable")
    }
    match checksum("/etc/hostname") {
        Ok(n) => println("checksum ${n}")
        Err(e) => println("unreadable")
    }
}
```

## Metadata

`fs.File.metadata(path)` returns kind flags, a byte size, and a
`fs.Permissions` record.

```atoll
import fs

fn describe(path string) string ! fs.Error {
    meta := fs.File.metadata(path)?
    kind := if meta.is_directory {
        "dir"
    } else if meta.is_symlink {
        "link"
    } else {
        "file"
    }
    p := meta.permissions
    return "${kind} ${meta.size}B r=${p.readable} w=${p.writable} x=${p.executable}"
}

fn main() void {
    match describe("/etc/hostname") {
        Ok(line) => println(line)
        Err(e) => println("no metadata")
    }
}
```

Metadata is a snapshot. Another process can extend, replace, or delete the file
between the `metadata` call and the read, so a size check is a cheap early
rejection, not a guarantee. Enforce the real limit while consuming the bytes
too, and never treat a prior `exists` check as a lock — just perform the
fallible operation and handle its failure.

## Open handles

`fs.File.open_read` and `fs.File.create` return an `fs.OpenFile` whose `read_into` /
`write_all` move bytes directly between the kernel and the guest allocation.
Use them when the size is unknown, can grow, or can be processed incrementally.

```atoll
import fs

fn total_bytes(path string) int ! fs.Error {
    f := fs.File.open_read(path)?
    mut buf: []byte = List.new[byte](4096)
    mut total := 0
    for {
        n := f.read_into(&mut buf, 4096)?
        if n == 0 {
            break
        }
        total = total + n
    }
    f.close()
    return total
}

fn main() void {
    match total_bytes("/etc/hostname") {
        Ok(n) => println("${n} bytes")
        Err(e) => println("read failed")
    }
}
```

`read_into` *appends* up to `max` bytes to the buffer and returns the count;
`0` means end of file. It never clears the buffer, so track consumed bytes
yourself — the loop above counts `n` rather than reading `buf.len()`.

`write_all` takes `[]byte` — owned or a window — and returns the number of
bytes written. `string.to_bytes()` produces that shape:

```atoll
import fs

fn save(path string, text string) int ! fs.Error {
    f := fs.File.create(path)?
    return f.write_all(text.to_bytes())?
}

fn main() void {
    match save("/tmp/atoll-book-save.txt", "hello") {
        Ok(n) => println("wrote ${n}")
        Err(e) => println("write failed")
    }
}
```

Handles close through `Drop`, including on an early `?` return, so a forgotten
`close()` never leaks a descriptor. Call `close()` explicitly only when the
resource must go before the end of scope, and never touch the handle
afterwards.

## Directories

`fs.Dir.list` yields the immediate entries; `fs.Dir.walk` recurses. A `fs.Entry`
carries the full `path` and its `name` (a window over the path), both a
`path.Path`, and its `kind`, an `fs.EntryKind`; `is_file()`, `is_directory()` and
`is_symlink()` ask it. A file whose name is not UTF-8 is an entry like any other:
its `path` opens it, and printing it writes U+FFFD for the bytes that are not
text.

```atoll
import fs

fn count_files(dir string) int ! fs.Error {
    entries := fs.Dir.list(dir)?
    mut files := 0
    for e in entries {
        if e.is_file() {
            files = files + 1
        }
        println("${e.name} (dir=${e.is_directory()} link=${e.is_symlink()}) ${e.path}")
    }
    return files
}

fn main() void {
    match count_files("/etc") {
        Ok(n) => println("${n} files")
        Err(e) => println("cannot list")
    }
}
```

Lifecycle mirrors `fs.File`: `create`, `create_all`, `delete`, `delete_all`,
`copy`, `move`, `exists`.

```atoll
import fs

fn setup(root string) int ! fs.Error {
    scratch := "${root}/tmp"
    fs.Dir.create_all("${root}/logs/archive")?
    fs.Dir.create(scratch)?
    println("tmp exists = ${fs.Dir.exists(scratch)}")

    fs.Dir.copy("${root}/logs", "${root}/logs-copy")?
    fs.Dir.move("${root}/logs-copy", "${root}/logs-backup")?
    all := fs.Dir.walk(root)?

    fs.Dir.delete(scratch)?
    fs.Dir.delete_all("${root}/logs-backup")?
    return all.len()
}

fn main() void {
    match setup("/tmp/atoll-book-root") {
        Ok(n) => println("${n} entries beneath root")
        Err(e) => println("setup failed")
    }
}
```

`fs.Dir.create` requires the parent to exist; `create_all` makes missing parents.
`fs.Dir.delete` requires an empty directory; `fs.Dir.delete_all` is recursive and
destructive — derive its target from validated application data, never from an
unchecked user string.

## Errors

`fs.Error` names the failures a caller can act on. Most variants carry the
offending `path`, a `path.Path` in the bytes the call was given; `ReadError` / `WriteError` add a host `message`, `Timeout`
adds `duration_ms`, `CrossesDevices` carries both paths, and `Other` carries
only a message.

Which path an error names is the one it is **about**. A copy or a move that
fails because of its destination names the destination — `File.copy(f, d)`
onto an existing directory `d` answers `IsDirectory { path: d }`, not a
statement about `f`.

Two variants have exactly one producer each, and they are worth knowing:
`AlreadyExists` comes from `Dir.create` and from `File.create_new`, the
exclusive open — `File.create` truncates and so cannot fail that way — and
`CrossesDevices` comes from a `move` whose two paths are on different
filesystems, which is the case a caller answers by copying and deleting
instead. `Timeout` is the kernel's own on a network mount, or an ambient
deadline armed with `time.push_deadline`.

```atoll
import fs

fn load_or_default(path string, fallback string) string {
    match fs.File.read(path) {
        Ok(text) => text
        Err(NotFound { path: p }) => fallback
        Err(PermissionDenied { path: p }) => "denied: ${p}"
        Err(ReadError { path: p, message: m }) => "read failed on ${p}: ${m}"
        Err(e) => "unclassified io failure"
    }
}

fn main() void {
    println(load_or_default("/etc/hostname", "localhost"))
}
```

Bind the error as `err` or `e`. `error` is a keyword, so the obvious spelling
does not even parse:

```atoll refused=ATOLL1016
import fs

fn load(path string) string ! fs.Error {
    match fs.File.read(path) {
        Ok(text) => Ok(text)
        Err(error) => Err(error)
    }
}
```

That produces `ATOLL1016: Invalid pattern`.

When mapping `fs.Error` onto your own error type, note that a variant with named
fields is constructed *unqualified*. The qualified form resolves to a
constructor function and is rejected:

```atoll fail
import fs

error UploadError { TooLarge { size: int } }

fn guard(path string) int ! UploadError {
    meta := fs.File.metadata(path)?
    if meta.size > 4096 {
        error UploadError.TooLarge { size: meta.size }
    }
    return meta.size
}
```

Write `error TooLarge { size: meta.size }` instead.

The handle-based operations (`open_read`, `create`, `read_into`, `write_all`)
answer the same variants the whole-file ones do, so `NotFound` and
`PermissionDenied` are told apart either way.

## A worked example

Import validation, staged write, and publish-by-rename — the shape most
applications actually need.

```atoll
import fs

error ImportError {
    TooLarge { limit: int, actual: int }
    NotAFile { path: string }
    Io       { message: string }
}

const MAX_IMPORT: int = 1048576

fn guard_size(path string) int ! ImportError {
    meta := match fs.File.metadata(path) {
        Ok(m) => m
        Err(NotFound { path: p }) => error Io { message: "no such file: ${p}" }
        Err(e) => error Io { message: "metadata failed" }
    }
    if !meta.is_file {
        error NotAFile { path: path }
    }
    if meta.size > MAX_IMPORT {
        error TooLarge { limit: MAX_IMPORT, actual: meta.size }
    }
    return meta.size
}

fn import_lines(path string) []string ! ImportError {
    guard_size(path.clone())?
    return match fs.File.read_lines(path) {
        Ok(lines) => lines
        Err(e) => error Io { message: "read failed" }
    }
}

fn stage_and_publish(dir string, name string, body string) int ! ImportError

{
    staged := "${dir}/${name}.staging"
    final := "${dir}/${name}"
    match fs.Dir.create_all(dir) {
        Ok(_) => {}
        Err(e) => error Io { message: "mkdir failed" }
    }
    match fs.File.write(staged, body) {
        Ok(_) => {}
        Err(e) => error Io { message: "write failed" }
    }
    match fs.File.move(staged, final) {
        Ok(_) => {}
        Err(e) => error Io { message: "publish failed" }
    }
    return body.len()
}

fn main() void {
    written := match stage_and_publish("/tmp/atoll-book", "notes.txt", "alpha\nbeta\n") {
        Ok(n) => n
        Err(TooLarge { limit, actual }) => {
            println("${actual} exceeds ${limit}")
            return
        }
        Err(NotAFile { path }) => {
            println("not a file: ${path}")
            return
        }
        Err(Io { message }) => {
            println("io: ${message}")
            return
        }
    }
    println("published ${written} bytes")

    match import_lines("/tmp/atoll-book/notes.txt") {
        Ok(lines) => println("read ${lines.len()} lines")
        Err(e) => println("import failed")
    }
}
```

Writing to a temporary file in the destination directory and then moving it
over the target is the standard way to avoid publishing a half-written file.
Atoll does not promise it is atomic: durability and overwrite semantics are
host-platform concerns, and a successful sequence of ordinary calls is not a
filesystem transaction. Database transactions do not cover filesystem changes
either.

## Capabilities and paths

Host capability policy can deny filesystem access even when the source
type-checks: a project whose `[host] allow` grants neither `std/fs` nor the
operation a call reaches is refused at compile time. List only what a project
actually needs, down to single operations such as `std/fs.File.write`. A grant
is the operation's public name, `std/fs.Dir.copy`, and the name of the host
operation behind it, `std/fs.dir_copy`, grants it too; a refusal says the
public one.
Type safety grants no ambient filesystem authority.

Paths keep host-platform semantics: `path.Path` reads `/` as the separator, as
Unix does. When joining a trusted root with user text,
containment must be validated *after* the platform's normalization and symlink
policy are applied. Rejecting literal `..` segments alone does not stop
absolute-path, separator, case-folding, or symlink escapes on every host.

Source: https://docs.atoll.workreef.dev/language/standard-library/files/index.mdx
