home ~ projects ~ socials

Get A List Of Files In A Single Directory In Rust

---
[dependencies]
anyhow = "1.0.98"
---

use anyhow::Result;
use std::fs;
use std::path::PathBuf;

fn main() -> Result<()> {
    let dir = PathBuf::from(".");
    let files = get_files_in_dir(&dir)?;
    files.iter().for_each(|f| println!("{}", f.display()));
    Ok(())
}

pub fn get_files_in_dir(dir: &PathBuf) -> Result<Vec<PathBuf>> {
    let files = fs::read_dir(dir)?
        .into_iter()
        .filter(|p| {
            if p.as_ref().unwrap().path().is_file() {
                true
            } else {
                false
            }
        })
        .map(|p| p.as_ref().unwrap().path())
        .filter(|p| {
            !p.file_name().unwrap().to_str().unwrap().starts_with(".")
        })
        .collect();
    Ok(files)
}
Output:
./read_first_line.txt
./image-from-resvg.png
./test.rs
./og_image.rs
./example-log.log
./_run_locally
./pixel.png
./config-sample.json
./svg-wrapped-text-test.png
./read_first_line.csv
./json_sample.json
./test.txt
./_active_nvim_run
./alfa.txt
./jinja-template.html
-- end of line --

References