Home
Map
File modified Date (fs metadata)Get the number of seconds since a file was modified on the disk with fs metadata.
Rust
This page was last reviewed on Nov 22, 2023.
Modified. Sometimes it is helpful to compute a timestamp of when a file was modified. In Rust programs this could be used to determine if a file needs to be parsed again.
With fs metadata, we can access information from the filesystem. And we can access the modified time. In Rust, this is a SystemTime, which we can convert to seconds with duration_since.
Example. Here we introduce the get_modified_secs function. This receives a path to a file, and it returns a usize that indicates the seconds since it was modified on the disk.
Start In get_modified_secs we panic if we cannot get the metadata for the file. Then we call modified() in a function chain.
Info With duration_since, we compute the number of seconds since the start of the UNIX time. Then we call as_secs() to get a u64 number.
usize
use std::fs; pub fn get_modified_secs(file: &str) -> usize { // Get modification timestamp from file. let modified_date = fs::metadata(file).expect("Need metadata"); let secs = modified_date .modified() .expect("Need modified date") .duration_since(std::time::UNIX_EPOCH) .expect("Need duration") .as_secs(); secs.try_into().unwrap() } fn main() { let modified = get_modified_secs("programs/example.txt"); println!("MODIFIED TIMESTAMP: {}", modified); }
MODIFIED TIMESTAMP: 1692807807
Some notes. In Rust we have to specify some of our logic carefully—we must compute a duration to get a figure in seconds. The result is an accurate timestamp for the modified time for the file.
File
Summary. By computing a modified timestamp, we can more effectively determine the freshness of files on disk. And we can then update other files only as needed (as an optimization).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 22, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.