rust读取文件目录下的文件,形参是文件目录的路径,返回一个值为{path:文件目录下的文件的文件名,name:文件路径,isDir:是否为文件夹}组成的对象的数组
时间: 2024-04-12 21:30:46 浏览: 19
你可以使用一个 `Vec` 来存储文件的信息,然后将其作为函数的返回值。下面是一个示例代码:
```rust
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug)]
struct FileInfo {
path: String,
name: String,
is_dir: bool,
}
fn read_directory_files(path: &Path) -> Vec<FileInfo> {
let mut files = Vec::new();
if let Ok(entries) = fs::read_dir(path) {
for entry in entries {
if let Ok(entry) = entry {
let entry_path = entry.path();
if let Some(file_name) = entry_path.file_name() {
if let Some(file_name_str) = file_name.to_str() {
let is_dir = entry_path.is_dir();
files.push(FileInfo {
path: file_name_str.to_string(),
name: entry_path.to_string_lossy().to_string(),
is_dir,
});
}
}
}
}
}
files
}
fn main() {
let path = Path::new("path/to/directory");
let files = read_directory_files(&path);
for file in files {
println!("File path: {}", file.path);
println!("File name: {}", file.name);
println!("Is directory: {}", file.is_dir);
println!("----------------------");
}
}
```
在上面的示例中,我们定义了一个 `FileInfo` 结构体,用于存储文件的信息,包括路径、文件名和是否为文件夹。`read_directory_files` 函数遍历目录中的每个条目,并将文件的信息存储到 `files` 向量中。
在 `main` 函数中,我们调用 `read_directory_files` 函数来获取文件的信息,并遍历打印每个文件的路径、文件名和是否为文件夹。
请将示例代码中的 `"path/to/directory"` 替换为你实际想要读取的目录的路径。
相关推荐
![](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)
![](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)