Search code examples
filefor-looprustmetadata

Rust: I want to get last modified file in a dir


Language: Rust

I have done this already in Python:

file = max([f for f in os.scandir("files")], key=lambda x: x.stat().st_mtime).name

And now i want to get that in rust too.

I want to get the last modified file in a dir. this is how i read the dir:

let filecheck = fs::read_dir(path)
for path in filecheck {
   
}

but i dont know how to use the metadata::modified function to get the list of modified dates and then get the latest one.

I tried to use metadata::modified function and expected to get the result i want. What i got where errors.


Solution

  • In the future, please describe what errors you encounter while attempting a problem.

    Here's a rust snippet that scans the current directory and prints out the most recent file:

    let last_modified_file = std::fs::read_dir(my_directory_path)
        .expect("Couldn't access local directory")
        .flatten() // Remove failed
        .filter(|f| f.metadata().unwrap().is_file()) // Filter out directories (only consider files)
        .max_by_key(|x| x.metadata().unwrap().modified().unwrap()); // Get the most recently modified file
    
    println!("Most recent file: {:?}", last_modified_file);
    

    Notice the several uses of expect and unwrap. Accessing file metadata is not guaranteed to succeed. The program above assumes it always will succeed for the sake of simplicity.