# std::path

以跨平台的方式組合、拆解與檢查檔案路徑。

## 這個模組做什麼

路徑看起來像字串，但直接用字串拼接很容易出錯：Windows 用 `\`、Unix 用 `/`；檔名可能不是合法 UTF-8；要取副檔名還得自己找最後一個點。`std::path` 提供專門的路徑型別，幫你處理這些細節。

| 型別 | 類比 | 用途 |
| --- | --- | --- |
| `Path` | `str` | 借用的路徑，函式參數常用 `&Path` |
| `PathBuf` | `String` | 擁有所有權、可修改的路徑 |

兩者的關係就像 `&str` 與 `String`（見 [std::string](/pkg-string)）。底層存的是 `OsStr`／`OsString`（見 [std::ffi](/pkg-ffi)），所以能表示作業系統允許、但不是 UTF-8 的檔名。

大部分 `Path` 方法只做字串層面的處理，**不會碰到磁碟**；只有 `canonicalize`、`exists`、`is_file` 這類方法會真的查詢檔案系統。實際讀寫檔案見 [std::fs](/pkg-fs)。

## 匯入

```rust
use std::path::{Path, PathBuf};
```

本頁範例的路徑以 Unix 風格示範（macOS／Linux 上執行）。在 Windows 上，分隔符號是 `\`，且 `C:\` 這類開頭才算絕對路徑，輸出會不同。

## 常用 API

### Path 與 PathBuf：借用與擁有

`Path::new` 把字串（或任何 `AsRef<OsStr>`）包成 `&Path`，不會配置記憶體。`PathBuf` 則可以 `push` 加一段、`pop` 去掉最後一段。`PathBuf` 能自動解參考（deref）成 `&Path`，所以接受 `&Path` 的函式也能直接傳 `&PathBuf`。

`Path` 不實作 `Display`，要印出來得呼叫 `display()`。

簽名：

```rust
pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path;
pub fn push<P: AsRef<Path>>(&mut self, path: P);
pub fn pop(&mut self) -> bool;
pub fn display(&self) -> Display<'_>;
```

範例：

```rust
use std::path::{Path, PathBuf};

fn describe(p: &Path) {
    println!("{} (absolute: {})", p.display(), p.is_absolute());
}

fn main() {
    let borrowed: &Path = Path::new("/etc/hosts");
    describe(borrowed);

    let mut owned = PathBuf::from("/var");
    owned.push("log");
    owned.push("app.log");
    describe(&owned);

    owned.pop();
    describe(&owned);

    let relative = PathBuf::from("src/main.rs");
    describe(relative.as_path());
}
```

輸出：

```text
/etc/hosts (absolute: true)
/var/log/app.log (absolute: true)
/var/log (absolute: true)
src/main.rs (absolute: false)
```

### join：組合路徑

`join` 用平台正確的分隔符號把兩段路徑接起來，回傳新的 `PathBuf`，原路徑不變。這是組路徑的首選做法，比 `format!("{}/{}", a, b)` 安全。

簽名：

```rust
pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf;
```

注意：如果傳入的是絕對路徑，`join` 會直接以它**取代**原路徑，而不是接在後面（`push` 也一樣）。拿使用者輸入組路徑時要特別小心這點。

範例：

```rust
use std::path::Path;

fn main() {
    let base = Path::new("/home/user");
    let config = base.join(".config").join("app.toml");
    println!("{}", config.display());

    let replaced = base.join("/tmp/cache");
    println!("{}", replaced.display());

    let rel = Path::new("data").join("2024").join("01.csv");
    println!("{}", rel.display());
}
```

輸出：

```text
/home/user/.config/app.toml
/tmp/cache
data/2024/01.csv
```

### file_name 與 file_stem：取得檔名

`file_name` 回傳路徑最後一段；`file_stem` 回傳去掉最後一個副檔名的檔名。兩者都回傳 `Option<&OsStr>`：路徑是 `/` 或以 `..` 結尾時沒有檔名，回傳 `None`。結尾多一個 `/` 不影響結果。

簽名：

```rust
pub fn file_name(&self) -> Option<&OsStr>;
pub fn file_stem(&self) -> Option<&OsStr>;
```

範例：

```rust
use std::path::Path;

fn main() {
    for s in ["/srv/www/index.html", "archive.tar.gz", "/srv/www/", "/", "notes"] {
        let p = Path::new(s);
        println!("{:<20} name={:?} stem={:?}", s, p.file_name(), p.file_stem());
    }
}
```

輸出：

```text
/srv/www/index.html  name=Some("index.html") stem=Some("index")
archive.tar.gz       name=Some("archive.tar.gz") stem=Some("archive.tar")
/srv/www/            name=Some("www") stem=Some("www")
/                    name=None stem=None
notes                name=Some("notes") stem=Some("notes")
```

### extension：副檔名

`extension` 回傳最後一個 `.` 之後的部分，不含點。以 `.` 開頭且沒有其他點的檔名（如 `.bashrc`）視為沒有副檔名。`with_extension` 回傳換掉副檔名的新路徑，`set_extension` 直接修改 `PathBuf`。

比對副檔名時，回傳值是 `Option<&OsStr>`，要和 `Some(OsStr::new("rs"))` 比較。

簽名：

```rust
pub fn extension(&self) -> Option<&OsStr>;
pub fn with_extension<S: AsRef<OsStr>>(&self, extension: S) -> PathBuf;
pub fn set_extension<S: AsRef<OsStr>>(&mut self, extension: S) -> bool;
```

注意：比對是區分大小寫的，`JPG` 與 `jpg` 不相等；需要不分大小寫時先轉成字串再用 `eq_ignore_ascii_case`。

範例：

```rust
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

fn main() {
    for s in ["photo.JPG", "archive.tar.gz", ".bashrc", "Makefile"] {
        println!("{:<15} {:?}", s, Path::new(s).extension());
    }

    let is_rust = Path::new("lib.rs").extension() == Some(OsStr::new("rs"));
    println!("is rust: {}", is_rust);

    let md = Path::new("report.txt").with_extension("md");
    println!("{}", md.display());

    let mut out = PathBuf::from("build/app");
    out.set_extension("exe");
    println!("{}", out.display());
}
```

輸出：

```text
photo.JPG       Some("JPG")
archive.tar.gz  Some("gz")
.bashrc         None
Makefile        None
is rust: true
report.md
build/app.exe
```

### parent 與 ancestors：上層目錄

`parent` 回傳去掉最後一段後的路徑。只有一段的相對路徑（`main.rs`）會得到空路徑 `""`，根目錄 `/` 則沒有上層，回傳 `None`。`ancestors` 從自己開始一路往上列出每一層。

簽名：

```rust
pub fn parent(&self) -> Option<&Path>;
pub fn ancestors(&self) -> Ancestors<'_>;
```

範例：

```rust
use std::path::Path;

fn main() {
    for s in ["/usr/local/bin/tool", "src/main.rs", "main.rs", "/"] {
        println!("{:<20} parent={:?}", s, Path::new(s).parent());
    }

    let p = Path::new("/a/b/c");
    let chain: Vec<String> = p.ancestors().map(|a| a.display().to_string()).collect();
    println!("{:?}", chain);
}
```

輸出：

```text
/usr/local/bin/tool  parent=Some("/usr/local/bin")
src/main.rs          parent=Some("src")
main.rs              parent=Some("")
/                    parent=None
["/a/b/c", "/a/b", "/a", "/"]
```

### components：逐段拆解

`components` 把路徑拆成一段段的 `Component` 列舉：根目錄、`.`、`..`、一般名稱，以及 Windows 的磁碟代號 `Prefix`。拆解時會順便去掉多餘的 `/` 與中間的 `.`，但**不會**消掉 `..`，因為在有符號連結時 `..` 的意義要查磁碟才知道。

相關的 `strip_prefix` 去掉開頭的一段路徑，`starts_with` 以「整段」為單位比對（`/home` 不算 `/homework` 的前綴）。

簽名：

```rust
pub fn components(&self) -> Components<'_>;
pub fn strip_prefix<P: AsRef<Path>>(&self, base: P) -> Result<&Path, StripPrefixError>;
pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool;
```

範例：

```rust
use std::path::{Component, Path};

fn main() {
    let p = Path::new("/opt/./app/../lib/x.so");
    for c in p.components() {
        let label = match c {
            Component::RootDir => "root".to_string(),
            Component::CurDir => "cur".to_string(),
            Component::ParentDir => "parent".to_string(),
            Component::Normal(name) => format!("normal({})", name.to_string_lossy()),
            Component::Prefix(_) => "prefix".to_string(),
        };
        println!("{}", label);
    }

    let docs = Path::new("/home/user/docs/a.txt");
    println!("{:?}", docs.strip_prefix("/home/user"));
    println!("{}", docs.starts_with("/home"));
}
```

輸出：

```text
root
normal(opt)
normal(app)
parent
normal(lib)
normal(x.so)
Ok("docs/a.txt")
true
```

### canonicalize：轉成實際的絕對路徑

`canonicalize` 會查詢檔案系統，把路徑轉成絕對路徑，解開 `.`、`..` 與符號連結，得到「這個檔案真正在哪裡」。它等同於 `fs::canonicalize`。

範例不印出完整路徑（每台機器的暫存目錄不同），只檢查結果的性質。

簽名：

```rust
pub fn canonicalize(&self) -> io::Result<PathBuf>;
```

注意：路徑不存在時回傳 `ErrorKind::NotFound`，所以不能拿它來「清理」尚未建立的路徑。在 Windows 上結果會帶 `\\?\` 前綴。

範例：

```rust
use std::env;
use std::fs;
use std::process;

fn main() -> std::io::Result<()> {
    let dir = env::temp_dir().join(format!("std-path-canon-{}", process::id()));
    fs::create_dir_all(dir.join("sub"))?;
    fs::write(dir.join("target.txt"), "hi")?;

    let messy = dir.join("sub").join("..").join(".").join("target.txt");
    let clean = messy.canonicalize()?;
    println!("absolute: {}", clean.is_absolute());
    println!("has '..': {}", clean.to_string_lossy().contains(".."));
    println!("file name: {:?}", clean.file_name());
    println!("same file: {}", clean == dir.join("target.txt").canonicalize()?);

    match dir.join("ghost.txt").canonicalize() {
        Ok(_) => println!("found"),
        Err(e) => println!("ghost: {:?}", e.kind()),
    }

    fs::remove_dir_all(&dir)?;
    Ok(())
}
```

輸出：

```text
absolute: true
has '..': false
file name: Some("target.txt")
same file: true
ghost: NotFound
```

## 重點整理

- `Path` 對應 `&str`、`PathBuf` 對應 `String`；函式參數用 `&Path` 或 `impl AsRef<Path>`
- 組路徑用 `join`，不要手動拼 `/`；傳入絕對路徑會整個取代
- `file_name`、`extension`、`parent` 都回傳 `Option`，要處理 `None`
- 多數方法只處理字串，不碰磁碟；`canonicalize` 會查磁碟，路徑必須存在
- 印路徑用 `display()`，轉字串用 `to_str()`（可能失敗）或 `to_string_lossy()`
