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.
CodePudding user response:
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:
use std::fs;
fn main() {
let mut entries: Vec<fs::DirEntry> = fs::read_dir(".").expect("Couldn't access local directory")
.flatten() // Remove failed
.collect();
entries.sort_by_cached_key(|f| f.metadata().unwrap().modified().unwrap());
println!("Most recent file: {:?}", entries[0]);
}
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.