Home > Software engineering >  find file with specific name recursively
find file with specific name recursively

Time:11-23

I'm trying to code a CLI application that finds all the cargo.toml in a directory. The code only prints out the cargo.toml file in the first directory and never prints out the cargo.toml files in sub directories. Here is the Code

pub fn find_cargo_files(dir: &Path) -> Result<Vec<String>> {
    let mut cargo_files: Vec<String> = Vec::new();
    if (!dir.exists()) {
        panic!("Directory not found");
    } else {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                Self::find_cargo_files(&path);
            }
            if path.is_file() && path.file_name().unwrap().to_str().unwrap().eq("Cargo.toml") {
                    cargo_files.push(path.to_str().unwrap().to_string());
            }
        }
    }
    Ok(cargo_files)
}

And here is the output:

Files : ["../test/Cargo.toml"]

And here is the directory tree structure:

├── Cargo.toml
└── files
    └── Cargo.toml

1 directory, 2 files

Thx everyone <3

CodePudding user response:

You have to append the newly found files to the current list of files after recursing:

pub fn find_cargo_files(dir: &Path) -> Result<Vec<String>> {
    let mut cargo_files: Vec<String> = Vec::new();
    if (!dir.exists()) {
        panic!("Directory not found");
    } else {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {

                if let Ok(sub) = Self::find_cargo_files(&path) {
                    cargo_files.extend(sub);
                }

            }
            if path.is_file()
                && path.file_name()
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .eq("Cargo.toml")
            {
                    cargo_files.push(path.to_str().unwrap().to_string());
            }
        }
    }
    Ok(cargo_files)
}
  • Related