#3.1. fs:::文件系统
本页内容
std::fs 模块提供涉及整个文件系统的操作:文件、目录、链接、权限等。其设计以 WASI Preview 2 基于能力的模型为起点;因此,所有操作都只通过 Dir 句柄进行。
#3.1.0. 参数规则
适用本层级通用的参数约定:
- 下文签名中的路径参数
Path是P: AsPath的简写。str和Path都可以传入(3.7.3a)。 - 写入函数的数据参数
data接受AsBytes(2.11.13)。可以传入str、List<u8>和Slice<u8>。
写入一侧接受 AsBytes;读取缓冲区是 SliceMut<u8>(由 read(buf) 填充,2.23.1)。
#3.1.1. 核心类型
核心类型包括:包装操作系统句柄的 Dir 和 File;用于遍历目录的 ReadDir 和 DirEntry;以及表示元数据和权限的 Metadata 和 Permissions。以何种方式打开文件,由打开它的函数名决定(3.1.1a);各种打开方式共用的选项是 OpenFlags 和 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 保存 Unix 模式位以及它们的只读视图。在 Windows 上只应用只读属性。setter 原地修改值,不返回任何内容:先 p.set_readonly(true);,再把 p 传给 File::set_permissions。set_readonly(false) 只添加所有者的写权限位,组和其他用户保持不变(Rust 的 set_readonly(false) 会让所有人都能写该文件)。Debug 以八进制显示这些位:Permissions { mode: 0o644, readonly: false }。
OpenFlags 和 CreateFlags 是选项记录(6.2.10):字面量只写出它要改变的字段(CreateFlags { read: true }),以后的版本可以添加带默认值的字段。os 指向目标自己的记录:在 Unix 上是 os::unix::fs::OsOpenFlags / OsCreateFlags,在 Windows 上是 os::windows::fs::OsOpenFlags / OsCreateFlags,在其他地方是空记录;某个目标的记录字面量在另一个目标上无法编译。这四个记录和 os::windows::fs::CreateFileParams 都实现了 Debug。
Unix 权限位本身通过 std::os::unix::fs 中的 PermissionsExt(仅 Unix 目标,在那里属于 prelude)读取和设置:Permissions::from_mode(m)、p.mode()、p.set_mode(m)。Permissions 没有固有的 from_mode / mode。创建模式就是用它构造的 CreateFlags.permissions。
// 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. 打开文件
每种打开方式都是单独的函数,Dir 和 File 上都有(File::x(..) 即 Dir::root().x(..)),因此写不出无效的组合:什么都不为而打开、以只读方式创建或截断、追加同时截断、新建同时截断。
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()
下表是规范性的:
| 函数 | 访问 | 不存在时 | 已存在时 | POSIX | Windows |
|---|---|---|---|---|---|
open(p, access) | access(默认 ReadOnly) | NotFound | 保留 | O_RDONLY / O_WRONLY / O_RDWR(Append、ReadAppend 时加 O_APPEND) | OPEN_EXISTING;GENERIC_READ / GENERIC_WRITE / FILE_APPEND_DATA |
create(p) | 写,带 read 时读写 | 创建 | 清空 | O_CREAT | O_TRUNC | OPEN_ALWAYS,已存在时再清空(保留属性) |
create_new(p) | 写 / 读写 | 创建 | AlreadyExists | O_CREAT | O_EXCL | CREATE_NEW |
open_or_create(p) | 写 / 读写 | 创建 | 保留,位置为 0 | O_CREAT | OPEN_ALWAYS |
append(p) | 追加 / 读加追加 | 创建 | 保留,在末尾写入 | O_CREAT | O_APPEND | OPEN_ALWAYS + FILE_APPEND_DATA |
始终成立的规则:在 Unix 上使用 O_CLOEXEC,在 Windows 上使用不可继承的句柄(子进程只能通过 Command 获得句柄);除非 os.share_mode 另有指定,Windows 的共享模式为读、写和删除;permissions 只在调用创建了文件时生效(Unix:在 umask 之前;Windows:只有只读属性)。create_new 把 path 处的任何东西都视为已存在,悬垂的符号链接也不例外。
打开时检查以下各项,在所有目标上都相同:
os.custom_flags(Unix)设置了由函数决定的位时为InvalidInput:访问位、O_CREAT、O_EXCL、O_TRUNC、O_APPEND、O_DIRECTORY、O_NOFOLLOW。消息会指出该位对应的函数,例如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 的标志只做添加。follow_symlinks: false且最后一个分量是符号链接时: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和重解析标记)。File永远不是目录:打开目录为IsADirectory,p: is a directory: open it with Dir::open_dir。- 其余情况都是操作系统的回答(
NotFound、AlreadyExists、PermissionDenied;Windows 的共享冲突是带操作系统错误码的PermissionDenied)。
访问方式与处置方式的组合中,有四种没有对应的函数:仅截断已存在的文件(写或读写),以及新建同时追加。可以使用 open(p, WriteOnly) 后接 set_len(0)、create_new(新文件的末尾就是开头),或者原始层:Unix 上的 DirExt::open_at(p, O_WRONLY | O_TRUNC),Windows 上带 TRUNCATE_EXISTING 的 DirExt::create_file。原始层除了添加 O_CLOEXEC 和 Dir 的路径规则之外不做任何检查。
#3.1.2. Dir 能力
Dir 是能力的单位。除了进程默认能力 root() 之外,工作目录、主目录和操作系统临时目录分别以 current()、home() 和 temp() 提供。拿到句柄后,几乎所有文件系统操作都可以在它下面进行(打开文件,创建、删除和重命名目录),复制会自动走 copy_file_range / FICLONE / clonefile 等 reflink 路径。
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
}
在内部,Dir 使用 openat 系列调用。Dir::root() 以外的 Dir 会拒绝绝对路径和含 .. 的路径,因此访问被限制在该目录之下。这项检查针对的是路径文本,所以跟随目录中的符号链接可能会到达目录之外。需要完全隔离时,还应同时使用操作系统沙箱。
#3.1.3. File 方法
除了普通的读写之外,File 还有带 UTF-8 校验的 read_to_str、用于同步到磁盘的 sync_all / sync_data、用于调整长度的 set_len 等。它提供查询和修改元数据与权限的方法,seek 和 try_clone 允许在 fd 层面进行操作。它还提供文件锁(如 Rust 1.89 的 File::lock)和内存映射(mmap)。
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
读写通过 io trait 进行(2.23),prelude 会引入它们:f.read(buf)、f.write_all(data)、f.read_to_str()。File 没有同名的固有方法。要按行读取,就用 io::BufReader 包装它。
File 实现了 Drop 和 io::Close,因此它是仿射的(2.13.4):let g = f 会移动它,try_clone() 会创建一个独立的句柄。它的关闭可能失败,所以要用 try f.close() 关闭它,或用 using 绑定它;在某条路径上让它未关闭就离开作用域是编译错误,而因错误离开的路径会释放它。操作系统句柄(File、Dir、套接字、mmap、子进程的 pidfd)只释放一次,即使通过 unsafe { marker::share(..) } 共享的句柄再次关闭它也是如此。
通过 File(或套接字)的一个副本进行的关闭,绝不会在另一个副本仍有调用进行中时释放句柄。close() 立即返回;进行中的调用在该句柄上完成,最后一个这样的调用释放它。关闭之后开始的调用以 InvalidInput 失败,从关闭起 as_raw_fd() 返回 -1。因此,调用永远不会落到关闭之后打开、恰好得到相同描述符编号的另一个文件上。
#Mmap
unsafe fn File::mmap(offset, len) 把从 offset(页大小的倍数)开始的 len 字节映射为只读共享映射。它是 unsafe 的,因为文件的其他写入者会在映射底下改变这些字节,而截断文件会导致读取出错。
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
映射通过 unmap 或在释放时(离开 using)解除;此后的读取看到的是空映射。as_bytes() 是映射内存的视图(取一部分用 m.as_bytes()[a:b]);保留到解除映射之后的视图不得再读取。
#3.1.4. 便捷函数(作用于 Dir::root())
为了不必到处携带 Dir 句柄,提供了作用于 Dir::root() 的便捷函数。简单读写、元数据查询和存在性检查等日常任务只需一行,原子写入和递归遍历等常用模式也在同一处提供。open 和 create 只接受路径:它们就是 File::open(path) 和 File::create(path),其他打开方式在 File 和 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 是一个 TryIterator(2.7.13):try for e in fs::read_dir(p) { .. }。它按操作系统返回的顺序产出条目,并跳过 . / ..。读取目录或条目元数据失败时,错误从 next 抛出并关闭该流;此后再调用 next 得到 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
}
时间以 SystemTime 获得(3.3.3)。status_changed 是内容或元数据的最后一次变更(Unix 的 ctime、Windows 的 ChangeTime),而不是创建时间。created 读取 macOS 的 st_birthtime、Linux 的 statx(4.11+)和 Windows 的 CreationTime;在内核或文件系统不保存创建时间的地方,它是一个 IoError(Unsupported)。
#lines
fs::lines<P: AsPath>(path: P) 是一个会抛出错误的生成器(yield fn .. throws (IoError) -> str),产出文件中去掉 \n / \r\n 的各行:try for line in fs::lines(p) { .. }。第一次 next 打开文件;在最后一行之后、抛出错误时或循环提前离开时关闭文件(refs-lang 4.11)。
#glob
fs::glob(pattern: str) throws (IoError) -> List<Path> 返回与 pattern 匹配的路径,已排序且无重复。模式按 / 分割;在一个分量中,* 匹配任意长度的字符序列,? 匹配一个字符,[abc] / [a-z] / [!a](或 [^a])匹配集合中的一个字符,未闭合的 [ 匹配它自身。** 分量匹配零个或多个目录。除非分量本身以 . 开头,否则通配符永远不匹配开头的 .。相对模式给出以 / 连接的相对路径。不含通配符的分量用 exists / metadata 检查;会进入以符号链接指向的目录。无法读取的目录会抛出错误。对应 Python 的 glob.glob(pattern, recursive=True)。
#walk
walk 按深度优先遍历。它先产出 root 本身,然后按名称排序产出每个目录中的条目。它和 ReadDir 一样是 TryIterator,但抛出错误后会继续:无法读取的目录或条目从 next 抛出,下一次 next 继续处理其余部分。
#write_atomic:标准 POSIX 模式
write_atomic 把创建临时文件、写入数据、fsync、rename 以及对父目录 fsync 这一标准模式封装在一次调用中。
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)
每个健壮的应用都需要这种模式;在 Rust 中由
tempfilecrate、在 Go 中由renameio填补了标准库的这一空白。Nabi 直接在 std 中提供同样的功能。
#3.1.4a. 异步文件 I/O(*_async)
上面的函数和方法会阻塞调用它的操作系统线程。要在任务中等待时让出工作线程,就 await 同一操作的 *_async 版本(命名规则与 3.2.0 net 相同)。普通函数无法挂起无栈协程,因此在任务中同步调用不会自行变成异步调用。
// 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 只有上述方法的孪生版本(unlock 从不等待)。Dir 的每个同步方法也都有 *_async 版本。两者的孪生版本都接受 ref self;只有 close_async 会消耗其接收者(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
read_dir_async(Dir 上的方法和便捷函数都一样)返回的 ReadDirStream 是一个 TryStream,它在阻塞线程池上每次读取 64 个条目,并把它们产出给 try for await。读到末尾或离开 using 时它会关闭目录,并且一点一点地读取大目录。
let logs = try await Dir::root().open_dir_async("logs");
using entries = try await logs.read_dir_async() {
try for await entry in entries {
...
}
}
要追加,就用 File::append_async(path)(不存在时创建)或 File::open_async(path, Append)(仅限已存在的文件)打开。
行为。 普通文件没有就绪状态(在 kqueue / epoll 中它们总是就绪的),所以每个 *_async 调用都在另一个操作系统线程上运行同名的阻塞调用(task::spawn_blocking),同时挂起任务。结果和错误与同步调用完全相同。
取消。 如果等待中的任务被取消(2.18.4),已经开始的调用会在后台运行至完成,只丢弃其结果。因此写入、删除和重命名等副作用仍然会发生。调用操作的是它自己的那份字节副本:被取消的 read_async 永远不会写入调用方的缓冲区,被取消的写入也永远不会读取调用方之后修改的字节。
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. 示例
下面的示例展示典型的流程,从简单读取到原子写入、沙箱设置、递归遍历,以及用于多进程并发的文件锁。
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. 模块映射 / 目标可用性
各项功能在各目标上的行为:
| 项 | linux/macos/windows | wasi | 说明 |
|---|---|---|---|
Dir/File 基础 | ✓ | ✓ | 与基于能力的 WASI 天然契合 |
write_atomic | ✓ | ✓ | 始终可用 |
lock_exclusive | ✓(flock/LockFileEx) | ✗ | 在 wasm32 上为 Unsupported |
try_clone(dup) | ✓ | ✗ | 在 wasm32 上为 Unsupported |
mmap | ✓ | ✗ | 在 wasm32 上为 Unsupported |
copy reflink | ✓(btrfs/APFS/XFS) | ✗ | 自动回退到普通复制 |
walk | ✓ | ✓ | |
set_permissions | ✓(Windows:只读属性) | ✓ | wasi 上没有权限位:只检查路径,不做其他事 |
os::unix::fs | linux、macos、freebsd | ✗ | PermissionsExt、DirExt::open_at、OsOpenFlags、OsCreateFlags、O_* |
os::windows::fs | windows | ✗ | DirExt::create_file、CreateFileParams、OsOpenFlags、OsCreateFlags、FILE_* |
在 wasi 上,OpenFlags.os 和 CreateFlags.os 是空记录。
在浏览器(wasm32-unknown-unknown)中,所有 fs 调用都报告 Unsupported:随附的 JS 主机预打开 / 并拒绝每一次调用。
发现错误? 在 GitHub 上编辑此页 最后更新: