rust操作read-dir
时间: 2023-12-31 15:05:42 浏览: 45
在 Rust 中,可以使用标准库中的`std::fs`模块来操作文件和目录。要读取目录下的文件和子录,可以使用`read_dir`函数。以下是一个简单示例代码:
```rust
std::fs;
fn main() {
// 指定目录路径
let dir_path = "/path/to/directory";
// 读取目录下的文件和子目录
if let Ok(entries) = fs::read_dir(dir_path) {
for entry in entries {
if let Ok(entry) = entry {
// 获取文件或子目录的名称
let file_name = entry.file_name();
println!("{}", file_name.to_string_lossy());
}
}
} else {
println!("Failed to read directory.");
}
}
```
在上面的示例中,`read_dir`函数返回一个`std::fs::ReadDir`类型的迭代器。通过迭代器可以遍历目录中的每个文件和子目录。在每次迭代中,我们可以使用`file_name`方法获取文件或子目录的名称,并将其打印出来。
请注意,你需要将`/path/to/directory`替换为你要读取的目录的实际路径。另外,记得处理可能的错误情况,例如目录不存在或无法读取目录。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)