lars.a
lars.a

Reputation: 81

Get filepath from glob-entry for use in fs::read_to_string

I read a directory with glob. I can print the filepath but im unable to get the path as a string to use it in 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);
    }
}

I got this error:

  --> 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<'_>`
   |

How can I get the full filepath from entry to use it in "fs::read_to_string" ?

Upvotes: 1

Views: 1376

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You don't need a string as std::fs::read_to_string takes a AsRef<Path> as argument.

You should simply use the entry's OK value, which is a Path:

let file_content = fs::read_to_string(entry.unwrap()).expect("...");

Note that a clean program would usually handle errors:

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
        }
    }
}

Upvotes: 2

Related Questions