> ## Content Index
> Fetch the complete content index at: https://yinguobing.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Rust文件系统相关操作
- URL: https://yinguobing.com/blog/rust-file-system-operations/
- Published: 2022-04-11T13:16:55.000Z
- Updated: 2022-04-11T13:16:55.000Z
- Description: 类似Python中的os包
- Author: 尹国冰
- Tags: Rust

在开发 `count_files` 这个项目时用到了几个Rust的标准库，这里列一下使用方法。

### 判断目标路径是否存在

使用 `std::path::Path` ，提供了文件路径相关操作。

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

fn main() {
    let target_path = Path::new("/a/b/c.d");
    assert_eq!(target_path.exists(), false);
}
```

### 判断目标路径是否是文件夹

同样是使用Path。

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

fn main() {
    let target_path = Path::new("/Users/Robin");
    assert_eq!(target_path.is_dir(), true);
}
```

### 列出目标路径下的全部对象

使用 `std::fs::read_dir()` 。

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

fn main() {
    let target_path = Path::new("/Users/Robin/data");
    let entries = fs::read_dir(target_path).unwrap();
    for entry in entries {
        if let Ok(entry) = entry {
            println!("{}", entry.path().to_str().unwrap());
        }
    }
}
```