#Getting most recently opened file

3 messages · Page 1 of 1 (latest)

sharp crown
#

I'm trying to get a function that will get the most recently modified file between a list of files. I'm not too sure why this is causing trouble but here is the code and outputs:

fn main() {
  let mut most_recent = most_recently_modified_file(vec!["file1.txt", "file2.txt", "file3.txt");
  println!("{}", most_recent);
}



fn most_recently_modified_file(files: Vec<String>) -> Option<String> {
    let mut most_recent_file: Option<String> = None;
    let mut most_recent_modified_time: Option<SystemTime> = None;

    for file in files {
        if let Ok(metadata) = fs::metadata(&file) {
            if let Ok(modified_time) = metadata.modified() {
                println!("Checking file: {}, Modified Time: {:?}", file, modified_time);
                if most_recent_modified_time.is_none() || modified_time > most_recent_modified_time.unwrap() {
                    println!("Updating most recent modified file from {:?} to {:?}", most_recent_file, file);
                    most_recent_modified_time = Some(modified_time);
                    most_recent_file = Some(file);
                }
            }
        }
        println!("");
    }
    most_recent_file
}

Here's the output

Checking file: file1.txt, Modified Time: SystemTime { intervals: 133442216232508345 }
Updating most recent modified file from None to "file1.txt"

Checking file: file2.txt, Modified Time: SystemTime { intervals: 133579482648308373 }
Updating most recent modified file from Some("file1.txt) to "file2.txt"

Checking file: file3.txt, Modified Time: SystemTime { intervals: 133579482639774468 }

file1.txt

I have no idea why file1.txt is returned. The function obviously tells you that it changes the most recent modified file from file1.txt TO file2.txt, and yet it returns file1.txt
ANY ideas as to why this is?

#

Feel free to ping with any questions/help etc

muted glen
#

That code shouldn't even compile, because Option<String> doesn't impl Display