#3.1. fs::: 파일 시스템
이 페이지의 내용
std::fs 모듈은 파일, 디렉터리, 링크, 권한 등 파일 시스템 전반의 연산을 정의합니다. 설계는 WASI Preview 2의 capability 기반 모델에서 출발합니다. 그래서 모든 연산은 Dir 핸들을 거쳐서만 일어납니다.
#3.1.0. 인자 규칙
tier 공통 인자 규약이 적용됩니다.
- 아래 시그니처의 경로 매개변수
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. 핵심 타입
핵심 타입은 세 묶음입니다. OS 핸들을 감싸는 Dir와 File, 디렉터리를 순회하는 ReadDir와 DirEntry, 메타데이터와 권한을 표현하는 Metadata와 Permissions입니다. 파일을 여는 방식은 그 파일을 여는 함수의 이름이 정합니다(3.1.1a). 모든 열기 방식이 함께 쓰는 설정은 OpenFlags와 CreateFlags 레코드입니다.
struct Dir { /* OS handle (file descriptor / HANDLE) */ }
struct File { /* OS handle */ }
struct ReadDir { /* Dir 항목의 TryIterator; Drop: 소유자가 해제하는 곳에서 닫힘 */ }
struct DirEntry { /* path + name + metadata */ }
struct Metadata { /* 종류, 크기, mode, 시각 */ }
/// `open`이 이미 있는 파일을 무엇을 하려고 여는지.
#[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: 마지막 심볼릭 링크는 FilesystemLoop
os: OsOpenFlags = OsOpenFlags {}; // 타깃별 설정 (3.1.6)
}
#[non_exhaustive]
struct CreateFlags { // Debug
read: bool = false; // 읽기로도 엶
permissions: Permissions = Permissions::default();
// 새로 만드는 파일의 권한, umask 적용 전
follow_symlinks: bool = true;
os: OsCreateFlags = OsCreateFlags {};
}
struct Permissions { .. } // Clone, Copy, PartialEq, Eq, Hash, Debug
impl Permissions {
fn readonly(self) -> bool; // 누구에게도 write bit 가 없음
fn set_readonly(ref self, readonly: bool); // true: write bit 를 모두 지움; false: 소유자의 것만 켬
}
impl Default for Permissions { ... } // 0o666 (Windows: 읽기 전용 아님)
Permissions는 Unix 모드 비트와, 거기서 읽어 낸 읽기 전용 여부를 담습니다. Windows에서는 읽기 전용 속성만 적용됩니다. 설정 메서드는 값을 그 자리에서 바꾸고 아무것도 돌려주지 않습니다. p.set_readonly(true);로 바꾼 다음 p를 File::set_permissions에 넘깁니다. set_readonly(false)는 소유자의 write bit만 켜고 그룹과 다른 사용자의 비트는 그대로 둡니다(Rust의 set_readonly(false)는 누구나 쓸 수 있는 파일로 만듭니다). Debug는 비트를 8진수로 보여 줍니다: 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; // 하위 12 비트 (0o7777) 만 남김
fn mode(self) -> u32;
fn set_mode(ref self, mode: u32); // 비트를 mode 로 바꿈 (from_mode 처럼)
}
impl PermissionsExt for Permissions { .. }
#[non_exhaustive]
struct OsOpenFlags { custom_flags: i32 = 0; } // open(2) 에 더하는 O_* 플래그
#[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)
// 타깃 libc 의 값
// 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_*; 0 이 아니면 SECURITY_SQOS_PRESENT 를 더함
}
#[non_exhaustive]
struct OsCreateFlags {
share_mode: u32 = ..; custom_flags: u32 = 0; security_qos_flags: u32 = 0;
attributes: u32 = 0; // FILE_ATTRIBUTE_HIDDEN 등; create 는 비우는 파일에도 더함
}
#[non_exhaustive]
struct CreateFileParams { // CreateFile2 + CREATEFILE2_EXTENDED_PARAMETERS
access: u32; // GENERIC_READ, FILE_APPEND_DATA 등; 0: 메타데이터만
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 상수
#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: 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를 거쳐서만 핸들을 받습니다). Windows의 공유 모드는 os.share_mode가 달리 말하지 않으면 읽기, 쓰기, 삭제입니다. 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입니다(UnixO_NOFOLLOW, WindowsFILE_FLAG_OPEN_REPARSE_POINT와 reparse 태그).File은 디렉터리가 아닙니다. 디렉터리를 열면IsADirectory이고, 메시지는p: is a directory: open it with Dir::open_dir입니다.- 그 밖에는 OS의 답을 그대로 씁니다(
NotFound,AlreadyExists,PermissionDenied; Windows의 공유 위반은 OS 코드와 함께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 capability
Dir는 capability의 단위입니다. 프로세스 기본 capability인 root() 말고도 작업 디렉터리, 홈, OS 임시 디렉터리를 각각 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; // using 으로 묶으면 해제 시 닫힘; let 으로 버리면 프로세스 끝까지 열림
fn metadata(self, path: Path) throws (IoError) -> Metadata;
fn symlink_metadata(self, path: Path) throws (IoError) -> Metadata; // 마지막 symlink 를 따라가지 않음
fn exists(self, path: Path) -> bool;
fn set_permissions(self, path: Path, perm: Permissions) throws (IoError); // 마지막 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;
// reflink 를 먼저 시도 (macOS: clonefileat), 안 되면 바이트 복사
fn symlink(self, target: Path, link: Path) throws (IoError);
fn hardlink(self, target: Path, link: Path) throws (IoError);
fn close(self) throws (IoError); // 핸들 해제; root() 나 이미 닫힌 경우 no-op
}
Dir는 내부에서 openat 계열을 씁니다. Dir::root()가 아닌 Dir는 절대 경로와 ..를 담은 경로를 거부합니다. 그래서 접근이 그 디렉터리 아래로 한정됩니다. 이 검사는 경로 문자열만 봅니다. 그래서 디렉터리 안의 심볼릭 링크를 따라가면 바깥으로 나갈 수 있습니다. 완전한 격리가 필요하면 OS의 샌드박스도 함께 씁니다.
#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, Dir::root() 위
fn close(self) throws (IoError); // 이후 호출은 InvalidInput 로 실패; 두 번째 close 는 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
// 파일 잠금
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);
// 메모리 매핑 (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: 쓰기는 곧장 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
읽기와 쓰기는 prelude가 들여오는 io 트레잇(2.23)을 거칩니다. f.read(buf), f.write_all(data), f.read_to_str()처럼 씁니다. File에는 같은 이름의 고유 메서드가 없습니다. 줄 단위로 읽으려면 io::BufReader로 감쌉니다.
File은 Drop과 io::Close를 구현하므로 affine입니다(2.13.4). let g = f는 값을 옮기고, try_clone()은 독립된 핸들을 만듭니다. 닫기가 실패할 수 있으므로 try f.close()로 닫거나 using으로 묶습니다. 어떤 경로에서든 닫지 않고 스코프를 벗어나면 컴파일 에러이고, 에러로 빠져나가는 경로는 핸들을 해제합니다. OS 핸들(File, Dir, 소켓, mmap, 자식의 pidfd)은 unsafe { marker::share(..) }로 나눈 핸들이 다시 닫더라도 한 번만 해제됩니다.
File(또는 소켓)의 한 복사본으로 닫아도, 다른 복사본으로 진행 중인 호출 아래에서 핸들이 해제되지는 않습니다. close()는 바로 돌아옵니다. 진행 중인 호출은 그 핸들로 끝까지 실행되고, 그런 호출 중 마지막 호출이 핸들을 해제합니다. 닫은 뒤에 시작하는 호출은 InvalidInput으로 실패하고, as_raw_fd()는 닫은 시점부터 -1을 돌려줍니다. 그래서 닫은 뒤에 열려 같은 디스크립터 번호를 받은 다른 파일에 호출이 닿는 일은 없습니다.
#Mmap
unsafe fn File::mmap(offset, len)는 offset(페이지 크기의 배수)에서 len 바이트를 읽기 전용 공유 매핑으로 매핑합니다. 이 함수가 unsafe인 이유는 두 가지입니다. 파일에 쓰는 다른 쪽이 매핑 아래의 바이트를 바꿀 수 있습니다. 그리고 파일을 자르면 읽기가 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>; // 매핑 자체, 복사 없음; unmap 뒤에는 비어 있음
fn to_list(self) -> List<u8>; // copy of every byte
fn unmap(self);
}
impl Drop for Mmap { ... } // unmaps
매핑은 unmap이나 drop(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): 있는 파일, 읽기 전용
fn create(path: Path) throws (IoError) -> File; // File::create(path): 만들거나 비움, 쓰기 전용
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; // 마지막 symlink 를 따라가지 않음
fn exists(path: Path) -> bool;
fn set_permissions(path: Path, perm: Permissions) throws (IoError); // Windows: 읽기 전용 속성
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; // TryIterator<Item = DirEntry, Error = IoError> 구현
#ReadDir / DirEntry
impl TryIterator for ReadDir { type Item = DirEntry; type Error = IoError; ... }
impl Drop for ReadDir { ... } // 스트림을 닫음
impl DirEntry {
fn path(self) -> Path; // 나열한 디렉토리의 경로에 이름을 이은 것
fn file_name(self) -> str;
fn metadata(self) -> Metadata; // 항목 자신의 것: symlink 를 따라가지 않음
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) { .. }처럼 씁니다. OS가 돌려주는 순서대로 항목을 내고 . / ..은 건너뜁니다. 디렉터리나 항목의 메타데이터를 읽다 실패하면 next가 던지고 스트림을 닫습니다. 그 뒤의 next는 none을 줍니다.
#Metadata
#[non_exhaustive]
enum FileType { File, Dir, Symlink, Other } // Clone, Copy, PartialEq, Eq, Hash, Debug; Other: 장치, 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; // 마지막 수정 시각
fn accessed(self) throws (IoError) -> SystemTime; // 마지막 접근 시각
fn status_changed(self) throws (IoError) -> SystemTime; // 내용이나 메타데이터가 마지막으로 바뀐 시각
fn created(self) throws (IoError) -> SystemTime; // 만든 시각; 기록이 없으면 Unsupported
}
시각은 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)는 파일의 줄을 \n / \r\n 없이 내는 throwing 제너레이터(yield fn .. throws (IoError) -> str)입니다: 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])는 집합의 문자 하나에 맞고, 닫히지 않은 [는 그 문자 자체입니다. ** 구성 요소는 디렉터리 0개 이상에 맞습니다. 와일드카드는 구성 요소가 .으로 시작하지 않는 한 맨 앞의 .에 맞지 않습니다. 상대 패턴은 /로 이은 상대 경로를 줍니다. 와일드카드 없는 구성 요소는 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);
// 내부 동작.
// 1. File::create_new(.config.toml.tmp.<pid>.<n>), n = 비어 있는 첫 번호
// 2. write data
// 3. fsync(temp)
// 4. rename(temp, config.toml) ← atomic
// 5. fsync(parent dir), Dir::open_dir 로 엶 (Windows: 동기화할 것 없음)
견고한 앱이라면 어디서나 이 패턴이 필요합니다. 그래서 Rust에서는
tempfile크레이트, Go에서는renameio가 std의 빈자리를 채워 왔습니다. Nabi는 같은 기능을 std에 바로 둡니다.
#3.1.4a. 비동기 파일 I/O(*_async)
위의 함수와 메서드는 호출한 OS 스레드를 막습니다. task 안에서 기다리는 동안 워커를 내주려면 같은 연산의 *_async 판을 await로 기다립니다. 이름 규칙은 3.2.0 net과 같습니다. 일반 함수는 스택 없는 코루틴을 중단할 수 없습니다. 그래서 동기 호출이 task 안에서 저절로 비동기가 되지는 않습니다.
// 편의 함수: 모두 async, exists_async 외에는 throws (IoError)
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 { /* 디렉토리 핸들 + 읽어 둔 batch */ }
impl TryStream for ReadDirStream { type Item = DirEntry; type Error = IoError; ... }
impl Drop for ReadDirStream { ... } // 닫음
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 호출은 같은 이름의 블로킹 호출을 다른 OS 스레드에서 실행하고(task::spawn_blocking), 그동안 task를 중단합니다. 결과와 에러는 동기 호출과 똑같습니다.
취소. 기다리던 task가 취소되어도(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;
// 단순 읽기
let bytes = try fs::read("data.txt");
let text = try fs::read_to_str("config.toml");
// 안전한 쓰기 (atomic)
try fs::write_atomic("output.json", json_bytes);
// 로그에 덧붙이기 (없으면 만듦)
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: .. 거부 (symlink 는 막지 못함)
// 재귀 순회
try for entry in fs::walk(Path::new("src")) {
if entry.path().extension() == "nabi" {
process(entry.path());
}
}
// File 잠금 (concurrent process)
using f = try File::open(path, WriteOnly) {
try f.lock_exclusive();
// critical section
} // ← unlock + close 자동
#3.1.6. 모듈 매핑 / 타깃 가용성
타깃별 기능 동작은 다음과 같습니다.
| 항목 | linux/macos/windows | wasi | 비고 |
|---|---|---|---|
Dir/File 기본 | ✓ | ✓ | cap 기반 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에는 권한 비트가 없음: 경로만 확인하는 no-op |
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에서 이 페이지 고치기. 마지막 수정