我读了一个带有 glob 的目录。我可以打印文件路径,但我无法将路径作为字符串获取以在 fs::read_to_string()
extern crate glob;
use glob::glob;
use std::fs;
fn main() {
let source_files_glob = "/my/sample/path/*.ext";
for entry in glob(source_files_glob).expect("Failed to read glob pattern") {
println!("{}", entry.unwrap().display());
let file_content = fs::read_to_string(entry.unwrap().display()).expect("Something went wrong reading the file");
println!("Content: {}", file_content);
}
}
我遇到了这个错误:
--> src/main.rs:12:28
|
12 | let file_content = fs::read_to_string(entry.unwrap().display()).expect("Something went wrong reading the file");
| ^^^^^^^^^^^^^^^^^^ the trait `std::convert::AsRef<std::path::Path>` is not implemented for `std::path::Display<'_>`
|
如何从条目中获取完整的文件路径以在“fs::read_to_string”中使用它?
最佳答案
您不需要像 std::fs::read_to_string
这样的字符串需要 AsRef<Path>
作为参数。
您应该简单地使用条目的 OK
值,这是一个 Path
:
let file_content = fs::read_to_string(entry.unwrap()).expect("...");
请注意,干净的程序通常会处理错误:
for entry in glob(source_files_glob).expect("Failed to read glob pattern") {
match entry {
OK(path) => {
println!("{}", path.display());
let file_content = fs::read_to_string(path).expect("...");
println!("Content: {}", file_content);
}
Err(e) => {
// handle error
}
}
}
关于rust - 从 glob-entry 获取文件路径以用于 fs::read_to_string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57690855/