Help, return recent file in directory

Hi everyone, this function return recent file, but gave me error in some directory, when exclude .jpg, .jpeg, etc:

// return last modified v3 ...
fn last_modified_v3(src: &Path) -> io::Result<String> {    
    let is_empty = match std::fs::read_dir(src) {
        Ok(mut entries) => {
            entries.next().is_none()
        },
        Err(_) => false
    };
    
    if is_empty {
        //println!("empty directory");
        Ok(String::from("empty folder"))
    } else {
        let current_dir = src;
        let last_modified_file = std::fs::read_dir(current_dir)
            .expect("Couldn't access local directory")
            .flatten() // Remove failed
            .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files)
            .filter(|entry| {
                    if let Some(file_name) = entry.file_name().to_str() {
                        !file_name.ends_with("jpg") &&
                        !file_name.ends_with("jpeg") &&
                        !file_name.ends_with("png") &&
                        !file_name.ends_with("gif") &&
                        !file_name.ends_with("webp") &&
                        !file_name.ends_with("txt")
                    } else {
                        false
                    }
            })
            .max_by_key(|x| x.metadata().unwrap().modified().unwrap()); // Get the most recently modified file
    
        let path = last_modified_file.expect("REASON 1").path();
        let path_str = path.file_stem().expect("REASON").to_str().unwrap().to_string();
        // get only number
        let number: String = path_str.chars()
                            .filter(|c|c.is_numeric())
                            .collect();
        Ok(number)
    }
}

and the error:
thread 'main' panicked at 'REASON 1', src/main.rs:446:39
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

Note: the error, only when i add this piece of code
.filter(|entry| {
if let Some(file_name) = entry.file_name().to_str() {
!file_name.ends_with("jpg") &&
!file_name.ends_with("jpeg") &&
!file_name.ends_with("png") &&
!file_name.ends_with("gif") &&
!file_name.ends_with("webp") &&
!file_name.ends_with("txt")
} else {
false
}
})

Please a better solution :woozy_face:

If you can't get a backtrace, add dbg! statements to find out where the problem is happening. Trying to guess what the problem is without any output is asking a lot from us, and you also did not show which line is src/main.rs:446:39.

In spite of that I have a guess, which is that the last_modified_file is None, due to the filtering you added, and then last_modified_file.expect is causing the panic that you're seeing.

Please learn how to debug by adding dbg! so you do not have to rely on others to guess what the problem is.

EDIT: The following line is telling you how to get a backtrace, and you should do this to see more info about the problem:
note: run with RUST_BACKTRACE=1 environment variable to display a backtrace

2 Likes

That would be my guess as well. Could it be that there are no image (or txt) files in the directory?

Also, why do you want to return Result? You never return an Err.

On a side note, you have some unnessecary conversions to and from String. This will be a problem if your file names and paths aren't valid utf8. I'd rewrite it a little: Rust Playground

1 Like

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.