#3.1. fs:: - file system
On this page
- 3.1.0. Argument rules
- 3.1.1. Core types
- 3.1.1a. Opening a file
- 3.1.2. Dir capability
- 3.1.3. File methods
- Mmap
- 3.1.4. Convenience functions (on Dir::root())
- ReadDir / DirEntry
- Metadata
- lines
- glob
- walk
- write_atomic - the standard POSIX pattern
- 3.1.4a. Asynchronous file I/O (*_async)
- 3.1.5. Examples
- 3.1.6. Module mapping / target availability
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
Pathin the signatures below is shorthand forP: AsPath. It accepts bothstrandPath(3.7.3a). - The data parameter
dataof write functions acceptsAsBytes(2.11.13).str,List<u8>andSlice<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.
struct Dir { /* OS handle (file descriptor / HANDLE) */ }
struct File { /* OS handle */ }
struct ReadDir { /* TryIterator over Dir entries; Drop: closed where its owner releases it */ }
struct DirEntry { /* path + name + metadata */ }
struct Metadata { /* kind, size, mode, times */ }
/// What `open` opens an existing file for.
#[non_exhaustive]
enum Access { ReadOnly, WriteOnly, ReadWrite, Append, ReadAppend } // Clone, Copy, PartialEq, Eq, Hash, Debug
#[non_exhaustive]
struct OpenFlags { // Debug
follow_symlinks: bool = true; // false: a final symbolic link is FilesystemLoop
os: OsOpenFlags = OsOpenFlags {}; // the target's knobs (3.1.6)
}
#[non_exhaustive]
struct CreateFlags { // Debug
read: bool = false; // also open for reading
permissions: Permissions = Permissions::default();
// a created file's permissions, before the umask
follow_symlinks: bool = true;
os: OsCreateFlags = OsCreateFlags {};
}
struct Permissions { .. } // Clone, Copy, PartialEq, Eq, Hash, Debug
impl Permissions {
fn readonly(self) -> bool; // no write bit for anyone
fn set_readonly(ref self, readonly: bool); // true: clears every write bit; false: adds the owner's only
}
impl Default for Permissions { ... } // 0o666 (Windows: not read-only)
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.
// std::os::unix::fs
trait PermissionsExt {
fn from_mode(mode: u32) -> Self; // keeps the low 12 bits (0o7777)
fn mode(self) -> u32;
fn set_mode(ref self, mode: u32); // sets the bits to mode (as from_mode)
}
impl PermissionsExt for Permissions { .. }
#[non_exhaustive]
struct OsOpenFlags { custom_flags: i32 = 0; } // more O_* flags for open(2)
#[non_exhaustive]
struct OsCreateFlags { custom_flags: i32 = 0; }
trait DirExt {
fn open_at(self, path: Path, oflag: i32, mode: u32 = 0o666) throws (IoError) -> File;
}
impl DirExt for Dir { .. }
const O_RDONLY: i32; O_WRONLY; O_RDWR; O_ACCMODE; O_CREAT; O_EXCL; O_TRUNC; O_APPEND;
O_NONBLOCK; O_NOCTTY; O_SYNC; O_DSYNC; O_NOFOLLOW; O_DIRECTORY; O_CLOEXEC;
O_DIRECT (linux, freebsd); O_NOATIME, O_TMPFILE (linux); O_PATH (linux, freebsd)
// the target's libc values
// std::os::windows::fs
#[non_exhaustive]
struct OsOpenFlags {
share_mode: u32 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
custom_flags: u32 = 0; // FILE_FLAG_WRITE_THROUGH, FILE_FLAG_SEQUENTIAL_SCAN, ..
security_qos_flags: u32 = 0; // SECURITY_*; SECURITY_SQOS_PRESENT added when non-zero
}
#[non_exhaustive]
struct OsCreateFlags {
share_mode: u32 = ..; custom_flags: u32 = 0; security_qos_flags: u32 = 0;
attributes: u32 = 0; // FILE_ATTRIBUTE_HIDDEN, ..; create also adds them to a file it empties
}
#[non_exhaustive]
struct CreateFileParams { // CreateFile2 + CREATEFILE2_EXTENDED_PARAMETERS
access: u32; // GENERIC_READ, FILE_APPEND_DATA, ..; 0: metadata only
disposition: u32; // CREATE_NEW .. TRUNCATE_EXISTING
share_mode: u32 = ..; attributes: u32 = 0; flags: u32 = 0; security_qos_flags: u32 = 0;
}
trait DirExt {
fn create_file(self, path: Path, params: CreateFileParams) throws (IoError) -> File;
}
impl DirExt for Dir { .. }
// + FILE_SHARE_*, GENERIC_*, FILE_*_DATA, CREATE_NEW .. TRUNCATE_EXISTING, FILE_ATTRIBUTE_*,
// FILE_FLAG_*, SECURITY_*, FILE_READ_ATTRIBUTES, FILE_WRITE_ATTRIBUTES, DELETE, SYNCHRONIZE constants
#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.
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:
| function | access | missing | exists | POSIX | Windows |
|---|---|---|---|---|---|
open(p, access) | access (default ReadOnly) | NotFound | kept | O_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 read | created | emptied | O_CREAT | O_TRUNC | OPEN_ALWAYS, then emptied when it existed (attributes kept) |
create_new(p) | write / read+write | created | AlreadyExists | O_CREAT | O_EXCL | CREATE_NEW |
open_or_create(p) | write / read+write | created | kept, position 0 | O_CREAT | OPEN_ALWAYS |
append(p) | append / read+append | created | kept, writes at the end | O_CREAT | O_APPEND | OPEN_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 isInvalidInput: 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: falseand 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(UnixO_NOFOLLOW; WindowsFILE_FLAG_OPEN_REPARSE_POINTand the reparse tag).- A
Fileis never a directory: opening one isIsADirectory,p: is a directory: open it with Dir::open_dir. - Everything else is the OS's answer (
NotFound,AlreadyExists,PermissionDenied; a Windows sharing violation isPermissionDeniedwith 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.
impl Dir {
fn root() -> Dir; // process default cap
fn current() throws (IoError) -> Dir; // current working dir
fn home() throws (IoError) -> Dir;
fn temp() throws (IoError) -> Dir; // OS temp dir
// open, create, create_new, open_or_create, append: 3.1.1a
fn open_dir(self, path: Path) throws (IoError) -> Dir;
fn read_dir(self) throws (IoError) -> ReadDir; // bound with using, closed on release; dropped via let, stays open until process exit
fn metadata(self, path: Path) throws (IoError) -> Metadata;
fn symlink_metadata(self, path: Path) throws (IoError) -> Metadata; // does not follow a final symlink
fn exists(self, path: Path) -> bool;
fn set_permissions(self, path: Path, perm: Permissions) throws (IoError); // follows a final symlink
fn create_dir(self, path: Path) throws (IoError);
fn create_dir_all(self, path: Path) throws (IoError);
fn remove_file(self, path: Path) throws (IoError);
fn remove_dir(self, path: Path) throws (IoError);
fn remove_dir_all(self, path: Path) throws (IoError);
fn rename(self, from: Path, to: Path) throws (IoError);
fn copy(self, from: Path, to: Path) throws (IoError) -> u64;
// tries reflink first (macOS: clonefileat), falls back to byte copy
fn symlink(self, target: Path, link: Path) throws (IoError);
fn hardlink(self, target: Path, link: Path) throws (IoError);
fn close(self) throws (IoError); // releases the handle; no-op on root() and when closed
}
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.
impl File {
// open, create, create_new, open_or_create, append: 3.1.1a, on Dir::root()
fn close(self) throws (IoError); // later calls fail with InvalidInput; a second close is a no-op
fn sync_all(self) throws (IoError); // fsync (data + metadata)
fn sync_data(self) throws (IoError); // fdatasync
fn set_len(self, size: u64) throws (IoError); // truncate
fn metadata(self) throws (IoError) -> Metadata;
fn permissions(self) throws (IoError) -> Permissions;
fn set_permissions(self, perm: Permissions) throws (IoError);
fn try_clone(self) throws (IoError) -> File; // dup fd
// file locking
fn lock_exclusive(self) throws (IoError); // flock LOCK_EX / LockFileEx
fn lock_shared(self) throws (IoError); // flock LOCK_SH
fn try_lock_exclusive(self) throws (IoError) -> bool;
fn unlock(self) throws (IoError);
// memory mapping (mmap)
unsafe fn mmap(self, offset: u64, len: usize) throws (IoError) -> Mmap;
}
impl io::Read for File { ... } // read, read_to_end, read_to_str, ..
impl io::Write for File { ... } // write, write_all, flush (no-op: writes go straight to the OS)
impl io::Seek for File { ... } // seek(io::SeekFrom), rewind, stream_position
impl io::AsyncRead for File { ... } // read_async, .. (3.1.4a)
impl io::AsyncWrite for File { ... }
impl io::AsyncSeek for File { ... }
impl io::Close for File { ... }
impl io::AsyncClose for File { ... } // close_async (3.1.4a)
// + AsRawFd, FromRawFd (unix); AsRawHandle, FromRawHandle (Windows): 3.10
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.
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).
fn open(path: Path) throws (IoError) -> File; // File::open(path): existing, read only
fn create(path: Path) throws (IoError) -> File; // File::create(path): created or emptied, write only
fn read(path: Path) throws (IoError) -> List<u8>;
fn read_to_str(path: Path) throws (IoError) -> str;
fn write<B: AsBytes>(path: Path, data: B) throws (IoError);
fn write_atomic<B: AsBytes>(path: Path, data: B) throws (IoError);
// tempfile + fsync + rename + fsync(parent)
fn metadata(path: Path) throws (IoError) -> Metadata;
fn symlink_metadata(path: Path) throws (IoError) -> Metadata; // does not follow a final symlink
fn exists(path: Path) -> bool;
fn set_permissions(path: Path, perm: Permissions) throws (IoError); // Windows: the read-only attribute
fn create_dir(path: Path) throws (IoError);
fn create_dir_all(path: Path) throws (IoError);
fn remove_file(path: Path) throws (IoError);
fn remove_dir(path: Path) throws (IoError);
fn remove_dir_all(path: Path) throws (IoError);
fn rename(from: Path, to: Path) throws (IoError);
fn copy(from: Path, to: Path) throws (IoError) -> u64;
fn symlink(target: Path, link: Path) throws (IoError);
fn hardlink(target: Path, link: Path) throws (IoError);
fn read_dir(path: Path) throws (IoError) -> ReadDir;
fn walk(root: Path) -> Walk; // implements TryIterator<Item = DirEntry, Error = IoError>
#ReadDir / DirEntry
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
#[non_exhaustive]
enum FileType { File, Dir, Symlink, Other } // Clone, Copy, PartialEq, Eq, Hash, Debug; Other: a device, pipe, socket, ...
impl FileType {
fn is_file(self) -> bool;
fn is_dir(self) -> bool;
fn is_symlink(self) -> bool;
} // + PartialEq, Debug
impl Metadata {
fn len(self) -> u64;
fn file_type(self) -> FileType;
fn is_file(self) -> bool;
fn is_dir(self) -> bool;
fn is_symlink(self) -> bool;
fn permissions(self) -> Permissions;
fn modified(self) throws (IoError) -> SystemTime; // last modification time
fn accessed(self) throws (IoError) -> SystemTime; // last access time
fn status_changed(self) throws (IoError) -> SystemTime; // last change of contents or metadata
fn created(self) throws (IoError) -> SystemTime; // creation time; Unsupported where none is kept
}
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.
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
tempfilecrate and in Gorenameiohave 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.
// convenience functions: all async, throws (IoError) except exists_async
async fn open_async(path: Path) throws (IoError) -> File;
async fn create_async(path: Path) throws (IoError) -> File;
async fn read_async(path: Path) throws (IoError) -> List<u8>;
async fn read_to_str_async(path: Path) throws (IoError) -> str;
async fn write_async<B: AsBytes>(path: Path, data: B) throws (IoError);
async fn write_atomic_async<B: AsBytes>(path: Path, data: B) throws (IoError);
async fn metadata_async(path: Path) throws (IoError) -> Metadata;
async fn symlink_metadata_async(path: Path) throws (IoError) -> Metadata;
async fn exists_async(path: Path) -> bool;
async fn set_permissions_async(path: Path, perm: Permissions) throws (IoError);
async fn create_dir_async(path: Path) throws (IoError);
async fn create_dir_all_async(path: Path) throws (IoError);
async fn remove_file_async(path: Path) throws (IoError);
async fn remove_dir_async(path: Path) throws (IoError);
async fn remove_dir_all_async(path: Path) throws (IoError);
async fn rename_async(from: Path, to: Path) throws (IoError);
async fn copy_async(from: Path, to: Path) throws (IoError) -> u64;
async fn symlink_async(target: Path, link: Path) throws (IoError);
async fn hardlink_async(target: Path, link: Path) throws (IoError);
async fn read_dir_async(path: Path) throws (IoError) -> ReadDirStream;
impl File {
async fn open_async(path: Path, access: Access = ReadOnly, flags: OpenFlags = OpenFlags {}) throws (IoError) -> File;
async fn create_async(path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn create_new_async(path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn open_or_create_async(path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn append_async(path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
// read_async, write_async, flush_async, seek_async, close_async, ..:
// io::AsyncRead / AsyncWrite / AsyncSeek / AsyncClose
async fn sync_all_async(ref self) throws (IoError);
async fn sync_data_async(ref self) throws (IoError);
async fn set_len_async(ref self, size: u64) throws (IoError);
async fn metadata_async(ref self) throws (IoError) -> Metadata;
async fn lock_exclusive_async(ref self) throws (IoError);
async fn lock_shared_async(ref self) throws (IoError);
}
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).
impl Dir {
async fn current_async() throws (IoError) -> Dir;
async fn home_async() throws (IoError) -> Dir;
async fn temp_async() throws (IoError) -> Dir;
async fn open_async(ref self, path: Path, access: Access = ReadOnly, flags: OpenFlags = OpenFlags {}) throws (IoError) -> File;
async fn create_async(ref self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn create_new_async(ref self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn open_or_create_async(ref self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn append_async(ref self, path: Path, flags: CreateFlags = CreateFlags {}) throws (IoError) -> File;
async fn open_dir_async(ref self, path: Path) throws (IoError) -> Dir;
async fn read_dir_async(ref self) throws (IoError) -> ReadDirStream;
async fn metadata_async(ref self, path: Path) throws (IoError) -> Metadata;
async fn symlink_metadata_async(ref self, path: Path) throws (IoError) -> Metadata;
async fn exists_async(ref self, path: Path) -> bool;
async fn set_permissions_async(ref self, path: Path, perm: Permissions) throws (IoError);
async fn create_dir_async(ref self, path: Path) throws (IoError);
async fn create_dir_all_async(ref self, path: Path) throws (IoError);
async fn remove_file_async(ref self, path: Path) throws (IoError);
async fn remove_dir_async(ref self, path: Path) throws (IoError);
async fn remove_dir_all_async(ref self, path: Path) throws (IoError);
async fn rename_async(ref self, from: Path, to: Path) throws (IoError);
async fn copy_async(ref self, from: Path, to: Path) throws (IoError) -> u64;
async fn symlink_async(ref self, target: Path, link: Path) throws (IoError);
async fn hardlink_async(ref self, target: Path, link: Path) throws (IoError);
async fn close_async(self) throws (IoError);
}
struct ReadDirStream { /* directory handle + batch read so far */ }
impl TryStream for ReadDirStream { type Item = DirEntry; type Error = IoError; ... }
impl Drop for ReadDirStream { ... } // closes
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.
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.
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.
use std::fs;
use std::fs::{Dir, File};
use std::path::Path;
// simple reads
let bytes = try fs::read("data.txt");
let text = try fs::read_to_str("config.toml");
// safe write (atomic)
try fs::write_atomic("output.json", json_bytes);
// appending to a log (created when missing)
using log = try File::append("app.log") {
try log.write_all("started\n");
}
// Dir capability (sandbox)
let data_dir = try Dir::root().open_dir("data");
using f = try data_dir.open("a.txt") { } // data/a.txt
using g = try data_dir.open("../etc/passwd") { } // IoError: .. rejected (symlinks are not blocked)
// recursive traversal
try for entry in fs::walk(Path::new("src")) {
if entry.path().extension() == "nabi" {
process(entry.path());
}
}
// File locking (concurrent process)
using f = try File::open(path, WriteOnly) {
try f.lock_exclusive();
// critical section
} // ← automatic unlock + close
#3.1.6. Module mapping / target availability
How each feature behaves on each target:
| Item | linux/macos/windows | wasi | Notes |
|---|---|---|---|
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::fs | linux, macos, freebsd | ✗ | PermissionsExt, DirExt::open_at, OsOpenFlags, OsCreateFlags, O_* |
os::windows::fs | windows | ✗ | 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