docs

#3.1. fs:: - file system

On this page

The std::fs module provides operations across the file system: files, directories, links, permissions and so on. The design starts from the capability-based model of WASI Preview 2; as a result, every op is performed only through a Dir handle.

#3.1.0. Argument rules

The tier-wide argument conventions apply:

  • The path parameter Path in the signatures below is shorthand for P: AsPath. It accepts both str and Path (3.7.3a).
  • The data parameter data of write functions accepts AsBytes (2.11.13). str, List<u8> and Slice<u8> can be passed.

The writing side accepts AsBytes; a read buffer is a SliceMut<u8> (filled by read(buf), 2.23.1).

#3.1.1. Core types

The core types are Dir and File, which wrap OS handles; ReadDir and DirEntry for iterating directories; and Metadata and Permissions for metadata and permissions. How a file is opened is the name of the function that opens it (3.1.1a); the knobs every way of opening shares are the records OpenFlags and CreateFlags.

Permissions holds Unix mode bits plus the read-only view of them. On Windows only the read-only attribute is applied. The setters change the value in place and return nothing: p.set_readonly(true);, then pass p to File::set_permissions. set_readonly(false) adds the owner's write bit and leaves group and others as they are (Rust's set_readonly(false) makes the file writable by everyone). Debug shows the bits in octal: Permissions { mode: 0o644, readonly: false }.

OpenFlags and CreateFlags are options records (6.2.10): a literal names only the fields it changes (CreateFlags { read: true }), and later releases may add fields with defaults. os names the target's own record: os::unix::fs::OsOpenFlags / OsCreateFlags on Unix, os::windows::fs::OsOpenFlags / OsCreateFlags on Windows, and an empty record elsewhere; a literal of one target's record does not compile on another. The four records and os::windows::fs::CreateFileParams implement Debug.

The Unix bits themselves are read and set through PermissionsExt in std::os::unix::fs (Unix targets only, in the prelude there): Permissions::from_mode(m), p.mode(), p.set_mode(m). Permissions has no inherent from_mode / mode. The create mode is CreateFlags.permissions built with it.

#3.1.1a. Opening a file

Each way of opening is its own function, on Dir and on File (File::x(..) is Dir::root().x(..)), so no invalid combination can be written: opening for nothing, creating or truncating read-only, append with truncate, create-new with truncate.

nabi
impl Dir {
    fn open(self, path: Path, access: Access = ReadOnly, flags: OpenFlags = OpenFlags {}) throws (IoError) -> File;
    fn create(self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
    fn create_new(self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
    fn open_or_create(self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
    fn append(self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
}
// File::open, File::create, File::create_new, File::open_or_create, File::append: the same, on Dir::root()

The table is normative:

functionaccessmissingexistsPOSIXWindows
open(p, access)access (default ReadOnly)NotFoundkeptO_RDONLY / O_WRONLY / O_RDWR (+O_APPEND for Append, ReadAppend)OPEN_EXISTING; GENERIC_READ / GENERIC_WRITE / FILE_APPEND_DATA
create(p)write, or read+write with readcreatedemptiedO_CREAT | O_TRUNCOPEN_ALWAYS, then emptied when it existed (attributes kept)
create_new(p)write / read+writecreatedAlreadyExistsO_CREAT | O_EXCLCREATE_NEW
open_or_create(p)write / read+writecreatedkept, position 0O_CREATOPEN_ALWAYS
append(p)append / read+appendcreatedkept, writes at the endO_CREAT | O_APPENDOPEN_ALWAYS + FILE_APPEND_DATA

Always: O_CLOEXEC on Unix and a non-inheritable handle on Windows (a child gets handles only through Command); the Windows share mode is read, write and delete unless os.share_mode says otherwise; permissions applies only when the call creates the file (Unix: before the umask; Windows: the read-only attribute only). create_new counts anything at path as existing, a dangling symbolic link too.

Checked at open, the same on every target:

  • os.custom_flags (Unix) setting a bit the function decides is InvalidInput: the access bits, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_DIRECTORY, O_NOFOLLOW. The message names the function for the bit, e.g. p: os.custom_flags sets O_TRUNC, which File::open_or_create decides: use File::create instead, or DirExt::open_at for raw flags. Windows flags only add.
  • follow_symlinks: false and the last component is a symbolic link: FilesystemLoop, p: is a symbolic link and follow_symlinks is false: open its target, or leave follow_symlinks: true (Unix O_NOFOLLOW; Windows FILE_FLAG_OPEN_REPARSE_POINT and the reparse tag).
  • A File is never a directory: opening one is IsADirectory, p: is a directory: open it with Dir::open_dir.
  • Everything else is the OS's answer (NotFound, AlreadyExists, PermissionDenied; a Windows sharing violation is PermissionDenied with the OS code).

Four points of access x disposition have no function: truncating an existing file only (write or read+write), and create-new with append. Use open(p, WriteOnly) then set_len(0), create_new (a new file's end is its start), or the raw layer: DirExt::open_at(p, O_WRONLY | O_TRUNC) on Unix, DirExt::create_file with TRUNCATE_EXISTING on Windows. The raw layer checks nothing beyond adding O_CLOEXEC and the Dir path rule.

#3.1.2. Dir capability

Dir is the unit of capability. Besides root(), the process default cap, the working directory, home and the OS temp directory are available as current(), home() and temp(). With a handle in hand, nearly every file system operation can be performed beneath it (opening files, creating, removing and renaming directories), and copies automatically use reflink paths such as copy_file_range / FICLONE / clonefile.

Internally, Dir uses the openat family. A Dir other than Dir::root() rejects absolute paths and paths containing .., so access is confined beneath that directory. This check is on the path text, so following a symlink inside the directory can lead outside it. When full isolation is required, use the OS sandbox as well.

#3.1.3. File methods

Besides ordinary read / write, File has read_to_str with UTF-8 validation, sync_all / sync_data for syncing to disk, set_len for adjusting length, and so on. Methods for querying and changing metadata and permissions are provided, and seek and try_clone allow fd-level manipulation. File locking (as Rust 1.89's File::lock) and memory mapping (mmap) are also provided.

Reading and writing go through the io traits (2.23), which the prelude brings in: f.read(buf), f.write_all(data), f.read_to_str(). File has no inherent methods of the same names. For line reads wrap it in io::BufReader.

File implements Drop and io::Close, so it is affine (2.13.4): let g = f moves it, and try_clone() makes an independent handle. Its close can fail, so close it with try f.close() or bind it with using; leaving its scope open on some path is a compile error, and a path that leaves with an error releases it. An OS handle (File, Dir, sockets, mmap, a child's pidfd) is released once, even when handles shared with unsafe { marker::share(..) } close it again.

A close through one copy of a File (or a socket) never releases the handle under a call in flight through another copy. close() returns at once; the call in flight finishes on the handle, and the last such call releases it. Calls that start after the close fail with InvalidInput, and as_raw_fd() returns -1 from the close on. So a call never reaches another file that was opened after the close and got the same descriptor number.

#Mmap

unsafe fn File::mmap(offset, len) maps len bytes at offset (a multiple of the page size) as a read-only shared mapping. It is unsafe because another writer of the file changes the bytes under the mapping, and truncating the file makes reads fault.

nabi
struct Mmap { /* address, length */ }

impl Mmap {
    fn len(self) -> usize;                         // 0 after unmap
    fn is_empty(self) -> bool;
    fn get(self, i: usize) -> u8 | none;           // none past the end
    fn as_bytes(self) -> Slice<u8>;                // the mapping itself, not copied; empty after unmap
    fn to_list(self) -> List<u8>;                  // copy of every byte
    fn unmap(self);
}

impl Drop for Mmap { ... }                         // unmaps

A mapping is unmapped by unmap or on drop (leaving using); reads after that see an empty mapping. as_bytes() views the mapped memory (m.as_bytes()[a:b] for a part); a view kept past the unmap must not be read.

#3.1.4. Convenience functions (on Dir::root())

So that a Dir handle need not be carried around everywhere, convenience functions operating on Dir::root() are provided. Everyday tasks such as simple reads and writes, metadata queries and existence checks take one line, and frequently needed patterns such as atomic writes and recursive traversal are exposed in the same place. open and create take the path only: they are File::open(path) and File::create(path), and the other ways of opening are on File and Dir (3.1.1a).

#ReadDir / DirEntry

nabi
impl TryIterator for ReadDir { type Item = DirEntry; type Error = IoError; ... }
impl Drop for ReadDir { ... }            // closes the stream

impl DirEntry {
    fn path(self) -> Path;               // the listed directory's path joined with the name
    fn file_name(self) -> str;
    fn metadata(self) -> Metadata;       // of the entry itself: a symlink is not followed
    fn file_type(self) -> FileType;      // = metadata().file_type()
    fn is_dir(self) -> bool;
    fn is_file(self) -> bool;
    fn is_symlink(self) -> bool;
}

ReadDir is a TryIterator (2.7.13): try for e in fs::read_dir(p) { .. }. It yields entries in the order the OS returns them and skips . / ... A failed read of the directory or of an entry's metadata is thrown from next and closes the stream; a next after it gives none.

#Metadata

Times are obtained as SystemTime (3.3.3). status_changed is the last change of the contents or the metadata (Unix ctime, Windows ChangeTime), not the creation time. created reads macOS st_birthtime, Linux statx (4.11+) and Windows CreationTime; it is an IoError (Unsupported) where the kernel or the file system keeps none.

#lines

fs::lines<P: AsPath>(path: P) is a throwing generator (yield fn .. throws (IoError) -> str) of the file's lines without \n / \r\n: try for line in fs::lines(p) { .. }. The first next opens the file; it closes after the last line, when an error is thrown, or when the loop leaves early (refs-lang 4.11).

#glob

fs::glob(pattern: str) throws (IoError) -> List<Path> returns the paths matching pattern, sorted and without duplicates. The pattern is split at /; in a component * matches any run of characters, ? one character, [abc] / [a-z] / [!a] (or [^a]) one character of a set, and an unclosed [ itself. A ** component matches zero or more directories. A wildcard never matches a leading . unless the component starts with one. A relative pattern gives relative paths, joined with /. A component without wildcards is checked with exists / metadata; symlinked directories are entered. An unreadable directory throws. Python: glob.glob(pattern, recursive=True).

#walk

walk traverses depth-first. It yields root itself first, and the entries in each directory sorted by name. It is a TryIterator like ReadDir, but goes on after a throw: an unreadable directory or entry is thrown from next, and the next next continues with the rest.

#write_atomic - the standard POSIX pattern

write_atomic encapsulates the standard pattern of creating a temporary file, writing the data, fsync, rename, and fsync of the parent directory, all in one call.

nabi
try fs::write_atomic("config.toml", new_config_bytes);
// internal behavior:
//   1. File::create_new(.config.toml.tmp.<pid>.<n>), n = the first free counter
//   2. write data
//   3. fsync(temp)
//   4. rename(temp, config.toml)   ← atomic
//   5. fsync(parent dir), opened with Dir::open_dir (Windows: nothing to sync)

Every robust application needs this pattern; in Rust the tempfile crate and in Go renameio have filled the gap in std. Nabi provides the same functionality directly in std.

#3.1.4a. Asynchronous file I/O (*_async)

The functions and methods above block the calling OS thread. To give up the worker while waiting inside a task, await the *_async version of the same operation (same naming rule as 3.2.0 net). An ordinary function cannot suspend a stackless coroutine, so a sync call does not become async on its own inside a task.

File has twins only for the methods above (unlock never waits). Dir also has a *_async version of every sync method. The twins of both take ref self; only close_async consumes its receiver (0.5.13).

The ReadDirStream of read_dir_async (on Dir and the convenience function alike) is a TryStream that reads entries 64 at a time on the blocking pool and yields them to try for await. It closes the directory when read to the end or when leaving using, and reads large directories a little at a time.

nabi
let logs = try await Dir::root().open_dir_async("logs");
using entries = try await logs.read_dir_async() {
    try for await entry in entries {
        ...
    }
}

To append, open with File::append_async(path) (created when missing) or File::open_async(path, Append) (existing only).

Behavior. Regular files have no readiness (they are always ready in kqueue / epoll), so each *_async call runs the blocking call of the same name on another OS thread (task::spawn_blocking) and suspends the task meanwhile. Results and errors are exactly those of the sync call.

Cancellation. If the waiting task is cancelled (2.18.4), a call that has already started runs to completion in the background and only its result is discarded. Side effects such as writes, deletions and renames therefore still happen. The call works on its own copy of the bytes: a cancelled read_async never writes into the caller's buffer, and a cancelled write never reads bytes the caller changes afterwards.

nabi
async fn load(path: str) throws (IoError) -> Config {
    let text = try await fs::read_to_str_async(path);
    return try parse(text);
}

#3.1.5. Examples

The following example walks through the typical flow, from simple reads to atomic writes, sandbox setup, recursive traversal and file locking for concurrent processes.

#3.1.6. Module mapping / target availability

How each feature behaves on each target:

Itemlinux/macos/windowswasiNotes
Dir/File basics✓✓Natural fit for cap-based WASI
write_atomic✓✓Always available
lock_exclusive✓ (flock/LockFileEx)✗Unsupported on wasm32
try_clone (dup)✓✗Unsupported on wasm32
mmap✓✗Unsupported on wasm32
copy reflink✓ (btrfs/APFS/XFS)✗automatic fallback to copy
walk✓✓
set_permissions✓ (Windows: read-only attribute)✓no permission bits on wasi: a no-op that checks the path
os::unix::fslinux, macos, freebsd✗PermissionsExt, DirExt::open_at, OsOpenFlags, OsCreateFlags, O_*
os::windows::fswindows✗DirExt::create_file, CreateFileParams, OsOpenFlags, OsCreateFlags, FILE_*

On wasi OpenFlags.os and CreateFlags.os are empty records.

In the browser (wasm32-unknown-unknown) every fs call reports Unsupported: the shipped JS host pre-opens / and refuses every call.

Found a mistake? Edit this page on GitHub. Last updated