Return vector of Files in Directory

Hello!

Googling I found this example:

use std::io;
use std::fs::{self, DirEntry};
use std::path::Path;

// one possible implementation of walking a directory only visiting files
fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry)) -> io::Result<()> {
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit_dirs(&path, cb)?;
            } else {
                cb(&entry);
            }
        }
    }
    Ok(())
}

But I cannot figure out how to use it - what is "cb"? I have never seen the "&dyn Fn.." syntax before ( new user). And how would I alter the function so that it would keep error checking but actually also output a vector of the files in the directory?

Kind regards

1 Like

cb here is a callback: code privided by the caller to be run once for each file found during the search. Fn(...) is special syntax for a closure trait which, in this case, is being passed as a reference to a trait object.

Similar code to build a vector might look like this (untested):

fn collect_files_from_dir(dir: &Path) -> io::Result<Vec<PathBuf>> {
    let mut result: Vec<PathBuf> = vec![];
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                result.extend(collect_files_from_dir(&path)?);
            } else {
                result.push(path);
            }
        }
    }
    Ok(result)
}

Thanks for the explanation! Ended up using "glob", but that also makes sense what you did.
Kind regards

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.