Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find file with specific name recursively

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

1 directory, 2 files

Thx everyone <3

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading