#3.1. fs:::檔案系統
本頁內容
std::fs 模組提供橫跨整個檔案系統的操作:檔案、目錄、連結、權限等。其設計以 WASI Preview 2 的能力(capability)模型為出發點;因此,每項操作都只能透過 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 上只套用唯讀屬性。設定方法會就地改變值且不回傳任何東西:先 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() 之外,工作目錄、home 和作業系統暫存目錄可分別透過 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、重新命名,以及對父目錄 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 上編輯此頁 最後更新: